Search code examples
javascriptgoogle-chrome-extensionmessaging

Chrome extension messaging API - detect when port is closed


In my extension I'm using multiple ports to communicate between different content scripts (using background.js as intermediary). When the user updates his settings, all active versions of content.js need to receive this information.

I'm currently holding a list in background.js that saves the ids of all active content.js ports. However as soon as a page gets reloaded, the old id becomes obsolete because the port is closed. I'd like to remove this id from the list again, to prevent the list size to become to big. How can I detect, that this port has been closed?

Code that sets up the port from 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)
});

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

Solution

  • See Port lifetime for more details, you could listen to runtime.Port.onDisconnect, which is fired when there are no valid ports at the other side of the channel.

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