Search code examples
google-chrome-extensionmessaging

Chrome extension - Messaging with multiple ports


In my extension, different content scripts connect to background.js to communicate with each other. The problem I'm having, is that when I receive a message on one port, I am not able to forward this information to the other port. The error I'm getting is:

Error: Attempting to use a disconnected port object

My code in background.js

chrome.runtime.onConnect.addListener(function(port) {
  if(port.name === "menuport") {
    port.onMessage.addListener(function(msg) {
      console.log('BGJS from menuport')
      console.log(msg)
      var page_port = chrome.runtime.connect({name: "pageport"});
      page_port.postMessage(msg);
    });
  } else if (port.name === "pageport") {
    port.onMessage.addListener(function(msg) {
      console.log('BGJS from pageport')
      console.log(msg)
    });
  }
});

The pageport is activated in content.js:

var page_port = chrome.runtime.connect({name: "pageport"});
page_port.postMessage({source: "page", status: "ready"});
page_port.onMessage.addListener(function(msg) {
    console.log(msg)
});

The menuport works with a similar script. The activation of both ports works, I can see in the console. However I can't post a message to a port from background.js.


Solution

  • On background.js, when you receive the onConnect callback, you need to store that port as a variable, so you can reuse it later. I see that you discard the port variable under the port.name=="pageport", which causes it to be garbage collected (and disconnected). Store it as window.page_port.

    I think you are trying to "connect" from both sides, which does not make sense.

    One side connects, the other waits for the onConnect event.