本文介绍了又一次有关:错误:尝试使用断开连接的端口对象,该怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的设置

background.js

background.js

var port = null;
function setPort() {
    chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
        port = chrome.tabs.connect(tabs[0].id, {name: "CONTENTSCRIPT"});
    });
}

// when i click on something, get the port and send a message
function clickHandler(e) {
    setPort();
    if (port) {
        port.postMessage({key: 'message', value: true});
    }
}

contentscript.js

contentscript.js

chrome.runtime.onConnect.addListener(function (port) {
    if (port.name == "CONTENTSCRIPT") {
        port.onMessage.addListener(function (msg) {
            console.log(msg);
        });
    }
});

我正在做的是单击随机选项卡上的contextMenu按钮并尝试发送消息.

what i am doing is clicking on a contextMenu button on random tabs and trying to send a meessage.

发生的是,我单击的第一行,没有任何反应,没有错误.我第二次单击该消息.

what happens is that first tine i click, nothing happens, no errors. the second time i click the message goes through.

如果我切换到另一个选项卡,然后单击菜单按钮,则会出现Error: Attempting to use a disconnected port object错误.如果我再次单击该消息,则发送成功

if i switch to another tab, and click on the menu button, i get the Error: Attempting to use a disconnected port object error. If i click again the message gets sent successfully

我尝试使用var port = chrome.runtime.connect({name: "CONTENTSCRIPT"});,但是每次连接端口断开时都会出现错误

I've tried to use var port = chrome.runtime.connect({name: "CONTENTSCRIPT"}); but that errors out with a disconnected port every time

想法?

推荐答案

您的问题在于chrome.tabs.query是异步的.

Your problem lies in the fact that chrome.tabs.query is asynchronous.

您执行setPort(),它会在query执行回调并设置端口之前立即返回.此时,port为空或引用上一个选项卡的端口.

You execute setPort(), that immediately returns before query executes the callback and sets up port. At this moment, port is either null or refers to your previous tab's port.

因此,您不会收到任何错误,也可能会收到错误消息,因为旧端口无效.

Therefore, you either get no error, or an error because the old port is invalid.

此后,query中的回调被执行,并为下一次通信设置了port.

After that happened, the callback in query gets executed and port is set up for the next communication.

因此,要解决此问题,您需要在呼叫链中设置端口之后发送消息.示例:

So, to fix that, you need to send the message after the port is set up in the call chain. Example:

function setPort(callback) {
    chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
        port = chrome.tabs.connect(tabs[0].id, {name: "CONTENTSCRIPT"});
        callback(port);
    });
}

function clickHandler(e) {
    setPort( function (port) {
        if (port) { port.postMessage({key: 'message', value: true}); }
    });
}


顺便说一句,您应该重用端口,这很重要.如果您每次都重新建立连接,最好使用sendMessage,尽管我想您只是使用上面的代码进行了测试.


by the way, you're supposed to reuse a port, it's kind of the point. If you're re-establishing the connection every time, you're better off with sendMessage, though I suppose you only used the code above for testing.

这篇关于又一次有关:错误:尝试使用断开连接的端口对象,该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 02:15