$x() function is not defined inside a Chrome extension, content script

假装没事ソ 提交于 2019-12-21 09:07:32

问题


$x("//a[contains(@href,'.jpg')]");

works as expected from the developer tools command prompt. But, when in an extension's content-script I get a '$x is not defined'.

Why is this not available in a content-script or is there a special way of accessing it inside a content-script / Chrome extension?

I'm using Chrome 22 on Debian.


回答1:


$x() is not part of the run-time environment of a web page or content script. It is a tool that is part of the Command Line API for Chrome's DevTools.

To use XPath in a content script, you need to do it the normal way, the DevTools convenient shortcut is not available.

Your code would look like this:

var jpgLinks    = document.evaluate (
    "//a[contains(@href,'.jpg')]",
    document,
    null,
    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
    null
);
var numLinks    = jpgLinks.snapshotLength;

for (var J = 0;  J < numLinks;  ++J) {
    var thisLink = jpgLinks.snapshotItem (J);
    console.log ("Link ", J, " = ", thisLink);
}

-- which is the kind of thing that $x() was doing for you, behind the scenes.


While you are at it, consider switching to CSS selectors. Then the same functionality is:

var jpgLinks    = document.querySelectorAll ("a[href$='.jpg']");
var numLinks    = jpgLinks.length;

for (var J = 0;  J < numLinks;  ++J) {
    var thisLink = jpgLinks[J];
    console.log ("Link ", J, " = ", thisLink);
}

-- which is much more palatable in my book.



来源:https://stackoverflow.com/questions/18432072/x-function-is-not-defined-inside-a-chrome-extension-content-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!