如何捕获(或了解)chrome.runtime.sendMessage端口错误?

时间:2013-06-11 18:17:35

标签: google-chrome google-chrome-extension google-chrome-app

当我尝试向另一个分机发送消息时,偶尔我可能有一个无效的ID(扩展名可能已被删除),但sendMessage并没有通知我这一点。据我所知,它只是打印到console.error

这是miscellaneous_bindings Chrome的源代码第235行:

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

结果,我的应用程序一遍又一遍地尝试发送消息。我唯一的提示是从sendResponse()发回的空响应,但任何应用都可以发送一个空的响应对象!我怎么知道它失败了?

1 个答案:

答案 0 :(得分:6)

sendResponse的回调中,请查看chrome.runtime.lastError属性。

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...
});