Chrome Extension: Get Page Variables in Content Script

后端 未结 9 947
抹茶落季
抹茶落季 2020-11-27 03:44

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

9条回答
  •  悲&欢浪女
    2020-11-27 04:28

    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.

提交回复
热议问题