Can the window object be modified from a Chrome extension?

前端 未结 7 2005
甜味超标
甜味超标 2020-11-29 02:26

I would like to make a Chrome extension that provides a new object inside window. When a web page is viewed in a browser with the extension loaded, I would like

相关标签:
7条回答
  • 2020-11-29 02:50

    After hours trying different attempts and facing security issues like CORS, I found ways to edit the window object on Chrome, Firefox and Safari. You need to use different strategies for each one:

    Chrome

    1. Add your script to content_scripts.
    2. Inside your script file, append a script to the page and make it run your custom code inline. Like this:
    ;(function() {
      function script() {
        // your main code here
        window.foo = 'bar'
      }
    
      function inject(fn) {
        const script = document.createElement('script')
        script.text = `(${fn.toString()})();`
        document.documentElement.appendChild(script)
      }
    
      inject(script)
    })()
    

    Firefox

    On Firefox, the solution above doesn't work due to a Content-Security-Policy error. But the following workaround is currently working, at least for now:

    1. Add 2 scripts to content_scripts, e.g. inject.js and script.js
    2. The inject script will get the full absolute url of the script.js file and load it:
    ;(function() {
      const b = typeof browser !== 'undefined' ? browser : chrome
    
      const script = document.createElement('script')
      script.src = b.runtime.getURL('script.js')
      document.documentElement.appendChild(script)
    })()
    
    1. Your script.js will contain your main code:
    ;(function() {
      // your main code here
      window.foo = 'bar'
    })()
    

    Safari

    It's very similar to Firefox.

    1. Create 2 javascript files, e.g. inject.js and script.js
    2. The inject script will get the full absolute url of the script.js file and load it:
    ;(function() {
      const script = document.createElement('script')
      script.src = safari.extension.baseURI + 'script.js'
      document.documentElement.appendChild(script)
    })()
    
    1. Your script.js will contain your main code:
    ;(function() {
      // your main code here
      window.foo = 'bar'
    })()
    

    Source code

    See full code here: https://github.com/brunolemos/simplified-twitter

    0 讨论(0)
  • 2020-11-29 02:58

    As others have pointed out, context scripts do not run in the same context as the page's, so, to access the correct window, you need to inject code into the page.

    Here's my take at it:

    function codeToInject() {
        // Do here whatever your script requires. For example:
        window.foo = "bar";
    }
    
    function embed(fn) {
        const script = document.createElement("script");
        script.text = `(${fn.toString()})();`;
        document.documentElement.appendChild(script);
    }
    
    embed(codeToInject);
    

    Clean and easy to use. Whatever you need to run in the page's context, put it in codeToInject() (you may call it whatever you prefer). The embed() function takes care of packaging your function and sending it to run in the page.

    What the embed() function does is to create a script tag in the page and embed the function codeToInject() into it as an IIFE. The browser will immediately execute the new script tag as soon as it's appended to the document and your injected code will run in the context of the page, as intended.

    0 讨论(0)
  • 2020-11-29 03:01

    You can't, not directly. From the content scripts documentation:

    However, content scripts have some limitations. They cannot:

    • Use chrome.* APIs (except for parts of chrome.extension)
    • Use variables or functions defined by their extension's pages
    • Use variables or functions defined by web pages or by other content scripts

    (emphasis added)

    The window object the content script sees is not the same window object that the page sees.

    You can pass messages via the DOM, however, by using the window.postMessage method. Both your page and content script listen to the message event, and whenever you call window.postMessage from one of those places, the other will receive it. There's an example of this on the "Content Scripts" documentation page.

    edit: You could potentially add some methods to the page by injecting a script from the content script. It still wouldn't be able to communicate back with the rest of the extension though, without using something like postMessage, but you could at least add some things to the page's window

    var elt = document.createElement("script");
    elt.innerHTML = "window.foo = {bar:function(){/*whatever*/}};"
    document.head.appendChild(elt);
    
    0 讨论(0)
  • 2020-11-29 03:01

    Content Scripts can call window methods which can then be used to mutate the window object. This is easier than <script> tag injection and works even when the <head> and <body> haven't yet been parsed (e.g. when using run_at: document_start).

    // In Content Script
    window.addEventListener('load', loadEvent => {
        let window = loadEvent.currentTarget;
        window.document.title='You changed me!';
    });
    
    0 讨论(0)
  • 2020-11-29 03:02

    I've been playing around with this. I found that I can interact with the window object of the browser by wrapping my javascript into a window.location= call.

    var myInjectedJs = "window.foo='This exists in the \'real\' window object';"
    window.location = "javascript:" + myInjectedJs;
    
    var myInjectedJs2 = "window.bar='So does this.';"
    window.location = "javascript:" + myInjectedJs2;
    

    It works, but only for the last instance of window.location being set. If you access the document's window object, it will have a variable "bar" but not "foo"

    0 讨论(0)
  • 2020-11-29 03:04

    Thanks to the other answers here, this is what I'm using:

    ((source)=>{
      const script = document.createElement("script");
      script.text = `(${source.toString()})();`;
      document.documentElement.appendChild(script);
    })(function (){
    
      // Your code here
      // ...
    
    })
    
    

    Works great, no issues.

    0 讨论(0)
提交回复
热议问题