Can the window object be modified from a Chrome extension?

前端 未结 7 2006
甜味超标
甜味超标 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 03:06

    A chrome extension's content_script runs within its own context which is separate from the window. You can inject a script into the page though so it runs in the same context as the page's window, like this: Chrome extension - retrieving global variable from webpage

    I was able to call methods on the window object and modify window properties by essentially adding a script.js to the page's DOM:

    var s = document.createElement('script');
    s.src = chrome.extension.getURL('script.js');
    (document.head||document.documentElement).appendChild(s);
    s.onload = function() {
        s.remove();
    };
    

    and creating custom event listeners in that injected script file:

    document.addEventListener('_my_custom_event', function(e) {
      // do whatever you'd like! Like access the window obj
      window.myData = e.detail.my_event_data;
    })
    

    and dispatching that event in the content_script:

    var foo = 'bar'
    document.dispatchEvent(new CustomEvent('_save_OG_Editor', {
      'detail': {
        'my_event_data': foo
      }
    }))
    

    or vice versa; dispatch events in script.js and listen for them in your extension's content_script (like the above link illustrates well).

    Just be sure to add your injected script within your extension's files, and add the script file's path to your manifest within "web_accessible_resources" or you'll get an error.

    Hope that helps someone \ (•◡•) /

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