Chrome extension - access to document / page variable from extension

I am trying to develop an extension that only works on the specified pages. If the page owner adds a global variable to his code (for example, ACCEPT_STATS = true; ), I want to execute the specified code.

I already bind my function to the onload event, I also found a solution on how to do this in Firefox:

 var win = window.top.getBrowser().selectedBrowser.contentWindow; if (typeof win.wrappedJSObject.ACCEPT_STATS !== 'undefined') { // code to run if global variable present } 

but I could not make this work in Chrome. Is there any way to access the global variable URL of the Chrome browser?

My extension code is entered as a content script.

+10
javascript google-chrome google-chrome-extension
source share
2 answers

Yes, including the script on the page is executed in an isolated context from the runtime script page.

However, you can work around the problem of isolated worlds by clicking inline script on the runtime context through the script tag added to the html document. After that, the inline script can create a custom event.

An included script in an isolated context can listen to this event and respond accordingly.

Thus, the code in your included script will look something like this:

 // inject code into "the other side" to talk back to this side; var scr = document.createElement('script'); //appending text to a function to convert it src to string only works in Chrome scr.textContent = '(' + function () { var check = [do your custom code here]; var event = document.createEvent("CustomEvent"); event.initCustomEvent("MyCustomEvent", true, true, {"passback":check}); window.dispatchEvent(event); } + ')();' //cram that sucker in (document.head || document.documentElement).appendChild(scr); //and then hide the evidence as much as possible. scr.parentNode.removeChild(scr); //now listen for the message window.addEventListener("MyCustomEvent", function (e) { var check = e.detail.passback; // [do what you need to here]. }); 
+14
source share

The javascript that runs on the page works in a different "isolated world" than the javascript you enter using content scripts. Google Chrome saves these two worlds for security reasons, and therefore you cannot just read window.XYZ in any window. Additional information on how isolated worlds work: http://www.youtube.com/watch?v=laLudeUmXHM

The correct way to implement this is to communicate with the page through the window.postMessage API. Here's how I do it:

  • Paste the contents of the script into each tab
  • Send a message to a tab through window.postMessage
  • If the page understands this message, it responds correctly (again through window.postMessage)
  • The content of the script executes the code that needs to be executed.

NTN

+1
source share

All Articles