Don Rhummy
Don Rhummy

Reputation: 25860

How catch (or know about) chrome.runtime.sendMessage Port Error?

When I try to send a message to another extension, occasionally I might have an invalid id (the extension may have been removed), but sendMessage does not ever notify me of this. As far as I can tell, it just prints to console.error:

This is miscellaneous_bindings Line 235 of Chrome's source code:

chromeHidden.Port.dispatchOnDisconnect = function(  portId, errorMessage)
{
    var port = ports[portId];
    if (port) {
        // Update the renderer's port bookkeeping, without notifying the browser.
        CloseChannel(portId, false);
        if (errorMessage) {
            lastError.set(errorMessage, chrome);
            //It prints: Port error: Could not establish connection. Receiving end does not exist.
            console.error("Port error: " + errorMessage);
        }
        try {
            port.onDisconnect.dispatch(port);
        } finally {
            port.destroy_();
            lastError.clear(chrome);
        }
    }
};

As a result, my app is left trying over and over to send a message. The only hint I have is an empty response send back from sendResponse(), but any app can send an empty response object! How do I know it failed?

Upvotes: 12

Views: 8172

Answers (1)

Rob W
Rob W

Reputation: 349102

In the callback of sendResponse, look at the chrome.runtime.lastError property.

chrome.runtime.sendMessage("ID of extension", "message", function(response) {
    var lastError = chrome.runtime.lastError;
    if (lastError) {
        console.log(lastError.message);
        // 'Could not establish connection. Receiving end does not exist.'
        return;
    }
    // Success, do something with response...
});

Upvotes: 17

Related Questions