Chrome扩展程序 - 具有多个端口的消息传递 [英] Chrome extension - Messaging with multiple ports

查看:208
本文介绍了Chrome扩展程序 - 具有多个端口的消息传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的扩展中,不同的内容脚本连接到background.js以相互通信。我遇到的问题是,当我在一个端口上收到消息时,我无法将此信息转发给其他端口。我收到的错误是:

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

我在background.js中的代码

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)
    });
  }
});

pageport在content.js中激活:

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)
});

menuport使用类似的脚本。两个端口的激活工作,我可以在控制台中看到。但是,我无法将消息发送到来自background.js的端口。

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.

推荐答案

在background.js上,当您收到onConnect回调,您需要将该端口存储为变量,以便稍后重用。我看到你放弃port.name ==pageport下的端口变量,这导致它被垃圾收集(和断开连接)。将它存储为window.page_port。

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.

一方连接,另一方等待onConnect事件。

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

这篇关于Chrome扩展程序 - 具有多个端口的消息传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆