one more time about: Error: Attempting to use a disconnected port object, how to?

帅比萌擦擦* 提交于 2019-12-10 10:49:16

问题


here is my setup

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

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

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.

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

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

ideas?


回答1:


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

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.

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

Edit: 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.



来源:https://stackoverflow.com/questions/22943988/one-more-time-about-error-attempting-to-use-a-disconnected-port-object-how-to

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