Chrome Extension: Get Page Variables in Content Script

后端 未结 9 951
抹茶落季
抹茶落季 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:29

    I actually worked around it using the localStorge API. Note: to use this, our contentscript should be able to read the localStorage. In the manifest.json file, just add the "storage" string:

    "permissions": [...,"storage"]
    

    The hijack function lives in the content script:

    function hijack(callback) {
        "use strict";
        var code = function() {
          //We have access to topframe - no longer a contentscript          
          var ourLocalStorageObject = {
            globalVar: window.globalVar,
            globalVar2: window.globalVar2
          };
          var dataString = JSON.stringify(ourLocalStorageObject);
          localStorage.setItem("ourLocalStorageObject", dataString);
        };
        var script = document.createElement('script');
        script.textContent = '(' + code + ')()';
        (document.head||document.documentElement).appendChild(script);
        script.parentNode.removeChild(script);
        callback();
      }
    

    Now we can call from the contentscript

    document.addEventListener("DOMContentLoaded", function(event) { 
        hijack(callback);
    });
    

    or if you use jQuery in your contentscript, like I do:

    $(document).ready(function() { 
        hijack(callback);
    });
    

    to extract the content:

    function callback() {
        var localStorageString = localStorage.getItem("ourLocalStorageObject");
        var ourLocalStorageObject= JSON.parse(localStorageString);
    
        console.log("I can see now on content script", ourLocalStorageObject);
        //(optional cleanup):
        localStorage.removeItem("ourLocalStorageObject");
    }
    

    This can be called multiple times, so if your page changes elements or internal code, you can add event listeners to update your extension with the new data.

    Edit: I've added callbacks so you can be sure your data won't be invalid (had this issue myself)

提交回复
热议问题