Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access window variable from Content Script [duplicate]

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 ?

like image 562
François Pérez Avatar asked Dec 10 '13 16:12

François Pérez


1 Answers

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); 
like image 152
François Pérez Avatar answered Oct 23 '22 20:10

François Pérez