【问题标题】:How to postMessage through port when websocket receives the word.?websocket接收到word时如何通过端口postMessage。?
【发布时间】:2023-03-15 12:36:02
【问题描述】:

我正在尝试使用 websocket 的 onMessage 函数,以便当它收到“go”这个词时,它将通过当前选项卡的端口发布消息。当前选项卡 ID 有效,但我不断收到错误 Uncaught TypeError: Cannot read property 'postMessage' of undefined.

ws.onmessage = function (evt) {  
if(evt.data == "connect"){
  rpwd = "helloworld";
    ports[curTabID].postMessage({text: rpwd});
}
};

【问题讨论】:

  • ports 是如何构建、维护的,您从哪里获得curTabID? -1 目前信息不足;阅读this help article,并相应地编辑您的帖子。

标签: javascript google-chrome-extension websocket


【解决方案1】:

问题在于我将端口和 tab.id 误认为是同一个东西。 postMessage 必须在端口上调用。我必须添加一个 onConnect 侦听器来获取打开的任何选项卡的端口。

var ports = {};
function onConnect(port) {
ports[port.sender.tab.id] = port;
}
chrome.extension.onConnect.addListener(onConnect);

在那之后,我需要知道我当前的标签 ID 是什么,以便我可以在由 onConnect 填充的 ports 数组中查找它。

var curTabID = 0;

chrome.tabs.onSelectionChanged.addListener(function(tabId) {
    curTabID = tabId;
});

由此,我能够获得发送 postMessage 所需的端口信息。

ws.onmessage = function (evt) {  
    if(evt.data == "connect"){
        rpwd = "helloworld";
        ports[curTabID].postMessage({text: rpwd});
}
};

我在这段代码上费了很大力气,所以我希望我能节省一些时间。

【讨论】:

  • 您不必像这样跟踪活动标签。 chrome.tabs.query({active: true, currentWindow: true}, ...); 将根据需要找到当前标签。
猜你喜欢
  • 1970-01-01
  • 2017-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-29
  • 2011-05-11
  • 1970-01-01
  • 2020-09-28
相关资源
最近更新 更多