Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension - access document/page variable from extension

I'm trying to develop extension that works only on specified pages - If page owner adds global variable into their code (for eg. ACCEPT_STATS = true;) I want to execute specified code.

I've already bind my function to the onload event, i've also found solution how to do that 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 couldn't make this work under Chrome. Is there any possibility to access document's global variable throw Chrome Extension code?

My extension's code is injected as a content-script.

like image 379
Tomasz Banasiak Avatar asked Feb 12 '14 15:02

Tomasz Banasiak


People also ask

Can Chrome extension read page content?

To use Read Aloud, navigate to the web page you want to read, then click the Read Aloud icon on the Chrome menu. In addition, the shortcut keys ALT-P, ALT-O, ALT-Comma, and ALT-Period can be used to Play/Pause, Stop, Rewind, and Forward. You may also select the text you want to read before activating the extension.

Can Chrome extensions communicate with each other?

In addition to sending messages between different components in your extension, you can use the messaging API to communicate with other extensions.


1 Answers

Yes, including script into the page does run in an isolated context from the pages runtime script.

However, it is possible to work around the isolated worlds issue by pushing inline script into the runtime context via a script tag appended to the document's html. That inline script can then throw a custom event.

The included script in the isolated context can listen for that event and respond to it accordingly.

So code in your included script would 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's 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].
});
like image 153
PatAtCP Avatar answered Sep 27 '22 22:09

PatAtCP