Chrome Extension - access document/page variable from extension

后端 未结 2 1896
执笔经年
执笔经年 2021-02-13 12:19

I\'m trying to develop extension that works only on specified pages - If page owner adds global variable into their code (for eg. ACCEPT_STATS = true;) I want to ex

相关标签:
2条回答
  • 2021-02-13 13:05

    The javascript running on the page is running in a different "isolated world" than the javascript that you inject using content scripts. Google Chrome keeps these two worlds separate for security reasons and therefore you can't just read window.XYZ on any window. More info on how isolated worlds work : http://www.youtube.com/watch?v=laLudeUmXHM

    The correct way of implementing this is by communicating with the page is via window.postMessage API. Here're how I would go about it :

    1. Inject a content script into each tab
    2. Send a message to the tab via window.postMessage
    3. If the page understands this message, it responds correctly (again via window.postMessage)
    4. Content script executes the code that it needed to execute.

    HTH

    0 讨论(0)
  • 2021-02-13 13:23

    Yes, including script into the page does run in an isolated context from the pages runtime script.

    However, it is possible to work around the isolated worlds issue by pushing inline script into the runtime context via a script tag appended to the document's html. That inline script can then throw a custom event.

    The included script in the isolated context can listen for that event and respond to it accordingly.

    So code in your included script would look something like this:

    // inject code into "the other side" to talk back to this side;
    var scr = document.createElement('script');
    //appending text to a function to convert it's src to string only works in Chrome
    scr.textContent = '(' + function () { 
      var check = [do your custom code here];
      var event = document.createEvent("CustomEvent");  
      event.initCustomEvent("MyCustomEvent", true, true, {"passback":check});
      window.dispatchEvent(event); } + ')();'
    //cram that sucker in 
    (document.head || document.documentElement).appendChild(scr);
    //and then hide the evidence as much as possible.
    scr.parentNode.removeChild(scr);
    //now listen for the message
    window.addEventListener("MyCustomEvent", function (e) {
      var check = e.detail.passback;
      // [do what you need to here].
    });
    
    0 讨论(0)
提交回复
热议问题