我试图在后台进程和内容脚本之间扩展一些消息传递处理。在正常的过程中,我的后台进程通过postMessage()发送消息,内容脚本通过另一个带有响应的通道进行回复。但是,如果内容脚本无法在页面上找到有效内容,我现在希望将后台进程扩展到其他内容。在查看此消息时,我发现向空白页或系统页发送消息时出现问题。由于标签没有加载内容脚本,因此没有任何内容可以接收发布的消息。这会在控制台日志中生成警告,但不会产生任何不良影响。但是:
// Called when the user clicks on the browser action.
//
// When clicked we send a message to the current active tab's
// content script. It will then use heuristics to decide which text
// area to spawn an edit request for.
chrome.browserAction.onClicked.addListener(function(tab) {
var find_msg = {
msg: "find_edit"
};
try {
// sometimes there is no tab to talk to
var tab_port = chrome.tabs.connect(tab.id);
tab_port.postMessage(find_msg);
updateUserFeedback("sent request to content script", "green");
} catch (err) {
if (settings.get("enable_foreground")) {
handleForegroundMessage(msg);
} else {
updateUserFeedback("no text area listener on this page", "red");
}
}
});
不起作用。我希望connect或postMessage抛出我可以捕获的错误,但是控制台日志中包含错误消息,包括:
Port: Could not establish connection. Receiving end does not exist.
但我最终没有收到捕获声明。
答案 0 :(得分:0)
最后我无法使用connect,我不得不使用一次性sendMessage(),它在响应进入时具有回调函数。然后可以查询成功和lastError的状态。代码现在看起来像这样:
// Called when the user clicks on the browser action.
//
// When clicked we send a message to the current active tab's
// content script. It will then use heuristics to decide which text
// area to spawn an edit request for.
chrome.browserAction.onClicked.addListener(function(tab) {
var find_msg = {
msg: "find_edit"
};
// sometimes there is no content script to talk to which we need to detect
console.log("sending find_edit message");
chrome.tabs.sendMessage(tab.id, find_msg, function(response) {
console.log("sendMessage: "+response);
if (chrome.runtime.lastError && settings.get("enable_foreground")) {
handleForegroundMessage();
} else {
updateUserFeedback("sent request to content script", "green");
}
});
});