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