2

I am trying to write a chrome extension in which I inject serveral different scripts which may potentially need to share data. I am trying to use message passing as described here.

I can send a message from one of the injected scripts to another, but I can't seem to be able to send anything back to the extension.

Code in the extension popup.js:

function injectLoad() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        // query the active tab, which will be only one tab
        //and inject the script in it
        chrome.tabs.executeScript(tabs[0].id, {file: "load.js"});
    });
}

function  initPopup(  ) {
    console.log( "starting" );
    window.addEventListener( "something", function( evt ) {
      alert( "got " + evt.detail );
    }, false );
}

document.getElementById( 'loadit' ).addEventListener( 'click', injectLoad );

initPopup();

Code in the injected script:

function loadit() {

    window.dispatchEvent(new CustomEvent("something", {data: 'whatever'}));
}

loadit(); 

I never seem to get the event triggered. Thanks

  • See the [architecture article](https://developer.chrome.com/extensions/overview#arch) - the popup is a separate page. Use [extension API messaging](https://developer.chrome.com/extensions/messaging). – wOxxOm May 14 '18 at 18:55
  • Also you don't need to use `chrome.tabs.query({active: true, currentWindow: true}` in the popup in order to get the tab.id for the `chrome.tabs.executeScript`, you can just pass `null` as the parameter to it which then defaults to the active tab of the current window. – Luka Čelebić May 14 '18 at 18:56

0 Answers0