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

前端 未结 2 2152
暗喜
暗喜 2021-02-15 03:44
$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 \

相关标签:
2条回答
  • 2021-02-15 04:41

    I suggest adding this function to your code:

    var xpath = function (xpathToExecute) {
        var result = [];
        var nodesSnapshot = document.evaluate(xpathToExecute, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
        for (var i = 0; i < nodesSnapshot.snapshotLength; i++) {
            result.push(nodesSnapshot.snapshotItem(i));
        }
        return result;
    }

    and Just calling it in place of $x

    0 讨论(0)
  • 2021-02-15 04:43

    $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.

    0 讨论(0)
提交回复
热议问题