Access window variable from Content Script [duplicate]

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);
injectScript( chrome.extension.getURL('/js/my_file.js'), 'body');

in my_file.js:

// Read your variable from here and do stuff with it

Leave a Comment