Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension: Get Page Variables in Content Script

Is there any way to retrieve a page's javascript variables from a Google Chrome Content Script?

like image 821
esqew Avatar asked Oct 17 '10 23:10

esqew


2 Answers

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!

like image 88
npdoty Avatar answered Oct 15 '22 06:10

npdoty


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.

like image 26
Liran Brimer Avatar answered Oct 15 '22 04:10

Liran Brimer