Chrome Extension: Get Page Variables in Content Script
I created a little helper method, have fun :)
to retrieve the window's variables "lannister", "always", "pays", "his", "debts", you execute the following:
var windowVariables = retrieveWindowVariables(["lannister", "always", "pays", "his", "debts"]);
console.log(windowVariables.lannister);
console.log(windowVariables.always);
my code:
function retrieveWindowVariables(variables) {
var ret = {};
var scriptContent = "";
for (var i = 0; i < variables.length; i++) {
var currVariable = variables[i];
scriptContent += "if (typeof " + currVariable + " !== 'undefined') $('body').attr('tmp_" + currVariable + "', " + currVariable + ");\n"
}
var script = document.createElement('script');
script.id = 'tmpScript';
script.appendChild(document.createTextNode(scriptContent));
(document.body || document.head || document.documentElement).appendChild(script);
for (var i = 0; i < variables.length; i++) {
var currVariable = variables[i];
ret[currVariable] = $("body").attr("tmp_" + currVariable);
$("body").removeAttr("tmp_" + currVariable);
}
$("#tmpScript").remove();
return ret;
}
please note that i used jQuery.. you can easily use the native js "removeAttribute" and "removeChild" instead.
If you really need to, you can insert a <script>
element into the page's DOM; the code inside your <script>
element will be executed and that code will have access to JavaScript variables at the scope of the window. You can then communicate them back to the content script using data-
attributes and firing custom events.
Sound awkward? Why yes, it is, and intentionally so for all the reasons in the documentation that serg has cited. But if you really, really need to do it, it can be done. See here and here for more info. And good luck!