Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/438.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在google chrome插件(javascript)中通过xpath获取元素值_Javascript_Xpath_Google Chrome Extension - Fatal编程技术网

在google chrome插件(javascript)中通过xpath获取元素值

在google chrome插件(javascript)中通过xpath获取元素值,javascript,xpath,google-chrome-extension,Javascript,Xpath,Google Chrome Extension,我想问一些具体的问题 我正在尝试使用GoogleChrome扩展实现一个应用程序,它从另一个Chrome扩展中获取xpath。然后找到元素的值并用它做一些事情 我在chrome插件中有一个监听器,它接收带有用户用光标指向的html元素xpath的JSON。例如/HTML/BODY/DIV[@id='viewport']/DIV[@id='main']/DIV[@id='cnt']/DIV[6]/DIV[@id='rcnt']/DIV[3]/DIV[@id='center'col']/DIV[@i

我想问一些具体的问题

我正在尝试使用GoogleChrome扩展实现一个应用程序,它从另一个Chrome扩展中获取xpath。然后找到元素的值并用它做一些事情

我在chrome插件中有一个监听器,它接收带有用户用光标指向的html元素xpath的JSON。例如
/HTML/BODY/DIV[@id='viewport']/DIV[@id='main']/DIV[@id='cnt']/DIV[6]/DIV[@id='rcnt']/DIV[3]/DIV[@id='center'col']/DIV[@id='search']/DIV[1]/DIV[@id='ires']/OL[@id='rso']/DIV[2]/LI[2]/DIV[1]/DIV[1]/DIV[1]/

我想得到那个元素的值。因此,如果:

<html>
<body>
<div>Hello<\div>
<body>

你能帮忙吗?xpath中没有错误-运行时错误的xpath不会引发异常,如果我用xpath检查Chrome中的元素,它看起来也正常。

错误的
文档
。看看第一个

您的背景脚本位于一个特殊的不可见页面中,
document
引用该页面

要访问当前选项卡的DOM,您需要在其中插入并执行代码

chrome.runtime.onConnectExternal.addListener(function (port) {
    port.onMessage.addListener(function (msg) {
        var index;

        if (msg != null) {
            //   console.log("Received message: " + msg);
            var objJSON = JSON.parse(msg);

            for (index = 0; index < objJSON.length; ++index) {
                var xpath = objJSON[index].xpath;
                var url = objJSON[index].url;

                if (xpath != "Not looking at browser") {

                        var xp = getElementByXPath(xpath); //returns null all the time
                        var value = xp.innerHTML;
                }
            }
        }

    });
});

var getElementByXPath = function (xPath) {
    var xPathResult = document.evaluate(xPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    return xPathResult.singleNodeValue;
};