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

不想你离开。 提交于 2019-12-06 08:14:54

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.

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