34

I have a Chrome Extension that is trying to find on every browsed URL (and every iframe of every browser URL) if a variable window.my_variable_name exists.

So I wrote this little piece of content script :

function detectVariable(){
    if(window.my_variable_name || typeof my_variable_name !== "undefined") return true;
    return false;
}

After trying for too long, it seems Content Scripts runs in some sandbox.

Is there a way to access the window element from a Chrome Content Script ?

François Pérez
  • 1,339
  • 2
  • 11
  • 12
  • 2
    BTW, you wouldn't have been trying for too long, if you had started at **[the docs](http://developer.chrome.com/extensions/content_scripts.html#execution-environment)**: _Content scripts execute in a special environment called an isolated world [...]_ – gkalpak Dec 10 '13 at 19:24
  • 2
    It is more complicated than this. I managed to `console.log` something that looked like a familiar `window` element (but was a dummy one). So I assumed the documentation was outdated, which sometimes happens with Chrome Extensions. I finally managed to solve my issue by injecting code that reads the variables into the page instead of trying to read it from the content script (see below) – François Pérez Dec 11 '13 at 08:00
  • 1
    I wrote a simple module that helps you run JavaScript code on a webpage from Chrome extensions easily. Might help anyone who gets here: https://github.com/bluzi/chrome-extension-execute-on-website – Eliran Pe'er Sep 28 '17 at 22:01

1 Answers1

71

One thing that is important to know is that Content Scripts share the same DOM as the current page, but they don't share access to variables. The best way of dealing with this case is, from the content script, to inject a script tag into the current DOM that will read the variables in the page.

in manifest.json:

"web_accessible_resources" : ["/js/my_file.js"],

in contentScript.js:

function injectScript(file, node) {
    var th = document.getElementsByTagName(node)[0];
    var s = document.createElement('script');
    s.setAttribute('type', 'text/javascript');
    s.setAttribute('src', file);
    th.appendChild(s);
}
injectScript( chrome.extension.getURL('/js/my_file.js'), 'body');

in my_file.js:

// Read your variable from here and do stuff with it
console.log(window.my_variable);
Clavin
  • 1,154
  • 8
  • 17
François Pérez
  • 1,339
  • 2
  • 11
  • 12