Hijacking a variable with a userscript for Chrome

后端 未结 1 687
刺人心
刺人心 2020-12-13 11:42

I\'m trying to change the variable in a page using a userscript. I know that in the source code there is a variable

var smilies = false;

I

相关标签:
1条回答
  • 2020-12-13 12:02

    In Content scripts (Chrome extensions), there's a strict separation between the page's global window object, and the content script's global object.

    • To inject the code, a script tag has to be injected.
    • Overwriting a variable is straightforward.
      Overwriting a variable, with the intention of preventing the variable from being overwritten requires the use of Object.defineProperty Example + notes.

    The final Content script's code:

    // This function is going to be stringified, and injected in the page
    var code = function() {
        // window is identical to the page's window, since this script is injected
        Object.defineProperty(window, 'smilies', {
            value: true
        });
        // Or simply: window.smilies = true;
    };
    var script = document.createElement('script');
    script.textContent = '(' + code + ')()';
    (document.head||document.documentElement).appendChild(script);
    script.parentNode.removeChild(script);
    
    0 讨论(0)
提交回复
热议问题