Chrome Extension - access document/page variable from extension

后端 未结 2 1895
执笔经年
执笔经年 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: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].
    });
    

提交回复
热议问题