Question

How can I make the wicked-good-xpath library available to a chrome extension's content page?

I've tried putting it in the manifest.json file but wgxpath.install() fails. In the example below, alert.js fires it's alert and injected.js runs and is available in the source tab. No WGXPath though.

  "content_scripts": [
    {
      "matches" : ["<all_urls>"],
      "js"      : ["res/js/alert.js", "res/js/wgxpath.install.js", "injected.js" ],
      "run_at"  : "document_end"
    }
  ],

Thanks

Was it helpful?

Solution

According to the docs for Wicked-Good-XPath, wgxpath.install() ensures that the XPAth evaluation function "...is defined on the window object.".

According to the docs for Chrome extension Content Scripts, the content scripts "live" in an isolated world (JS context) and as far as the window object properties are concerned:

"Each isolated world sees its own version of the object. Assigning to the object affects your independent copy of the object."


I haven't tried it myself, but most probably you need to have Wicket-Good-XPath in the JS context of the web-page (not the content script), so you should have your content script add a script element, with a src pointing to the wgxpath.install.js file and then execute wgxpath.install() in the JS context of the web-page.
Additionally, you need to add the wgxpath.install.js file to your extension's web_accessible_resources.

Sample code:

In manifest.json:

...
"content_scripts": [{
    ...
    "js": ["res/js/alert.js", "injected.js"],
    ...
}],
"web_accessible_resources": ["/res/js/wgxpath.install.js"]

In injected.js:

/* "Embed" `wgxpath.install.js` into the web-page */
var script = document.createElement("script");
script.type = "text/javascript";
script.src = chrome.extension.getURL("/res/js/wgxpath.install.js");
document.body.appendChild(script);

/* "Install" Wicked-Good-XPath into the web-pages context */
var script = document.createElement("script");
script.type = "text/javascript";
script.textContent = "wgxpath.install();";
document.body.appendChild(script);
/*Optionaly*/script.parentNode.removeChild(script);

Depending on how you want to use Wicked-Good-XPath, you will probably need to inject more code into the web-page's JS context (or device a way to communicate between the two JS contexts).


BTW, this answer is a very good reference of the several ways you can inject code or content scripts into a web-page, using a Chrome extension.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top