当我尝试向另一个分机发送消息时,偶尔我可能有一个无效的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()
发回的空响应,但任何应用都可以发送一个空的响应对象!我怎么知道它失败了?
答案 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...
});