Chrome 扩展消息传递 API - 检测端口何时关闭

Chrome extension messaging API - detect when port is closed

在我的扩展中,我使用多个端口在不同的内容脚本之间进行通信(使用 background.js 作为中介)。当用户更新他的设置时,content.js 的所有活动版本都需要接收此信息。

我目前在 background.js 中持有一个列表,其中保存了所有活动 content.js 端口的 ID。但是,一旦重新加载页面,旧的 id 就会过时,因为端口已关闭。我想再次从列表中删除此 id,以防止列表大小变得过大。我如何检测到此端口已关闭?

设置端口的代码content.js:

var page_port = chrome.runtime.connect({name: unique_id});
page_port.postMessage({source: "page", page_id: unique_id, status: "ready", url: url});
page_port.onMessage.addListener(function(msg) {
    console.log(msg)
});

background.js中的代码:

page_dict = []
chrome.runtime.onConnect.addListener(function(port) {
    window[port.name] = port
    port.onMessage.addListener(function(msg) {
        if (msg.source === 'page') {
            if (jQuery.inArray(port.name, page_dict === -1)) {
                page_dict.push(port.name)
            }
        }
    });
});

请参阅 Port lifetime for more details, you could listen to runtime.Port.onDisconnect,当通道的另一侧没有有效端口时会触发。

port.onDisconnect.addListener(function() {
    //Your logic
});