Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 570
Don Rhummy Avatar asked Jun 11 '13 18:06

Don Rhummy


1 Answers

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...
});
like image 88
Rob W Avatar answered Sep 22 '22 19:09

Rob W