Chrome extension - Messaging with multiple ports

百般思念 提交于 2020-01-23 18:24:45

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/36477679/chrome-extension-messaging-with-multiple-ports

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!