5

当我尝试向另一个扩展程序发送消息时,有时我的 id 可能无效(扩展程序可能已被删除),但 sendMessage 不会通知我这一点。据我所知,它只是打印到console.error

这是 Chrome 源代码的 miscellaneous_bindings 第 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(),但任何应用程序都可以发送空响应对象!我怎么知道它失败了?

4

1 回答 1

11

在 的回调中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...
});
于 2013-06-11T18:45:26.617 回答