Chrome Extension: Get Page Variables in Content Script

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

    As explained partially in other answers, the JS variables from the page are isolated from your Chrome extension content script. Normally, there's no way to access them.

    But if you inject a JavaScript tag in the page, you will have access to whichever variables are defined there.

    I use a utility function to inject my script in the page:

    /**
     * inject - Inject some javascript in order to expose JS variables to our content JavaScript
     * @param {string} source - the JS source code to execute
     * Example: inject('(' + myFunction.toString() + ')()');
     */
    function inject(source) {
      const j = document.createElement('script'),
        f = document.getElementsByTagName('script')[0];
      j.textContent = source;
      f.parentNode.insertBefore(j, f);
      f.parentNode.removeChild(j);
    }
    

    Then you can do:

    function getJSvar(whichVar) {
       document.body.setAttribute('data-'+whichVar,whichVar);
    }
    inject('(' + getJSvar.toString() + ')("somePageVariable")');
    
    var pageVar = document.body.getAttribute('data-somePageVariable');
    

    Note that if the variable is a complex data type (object, array...), you will need to store the value as a JSON string in getJSvar(), and JSON.parse it back in your content script.

提交回复
热议问题