0
我想擴展我的後臺進程和內容腳本之間的一些消息處理。在正常情況下,我的後臺進程通過postMessage()發送消息,內容腳本通過另一個響應回覆消息。但是,如果內容腳本在頁面上找不到有效內容,我現在想擴展後臺進程以回退到其他內容。在看這個時,我發送消息給空白頁面或系統頁面時發現問題。由於選項卡沒有加載內容腳本,因此沒有任何內容可以接收發布的消息。這會在控制檯日誌中生成警告,但不會產生不良影響。但是:我應該如何處理尚未加載內容腳本的Chrome標籤頁?
// 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");
}
}
});
不工作。我期望連接或postMessage的拋出的錯誤,我可以捕獲,但是控制檯日誌充滿了錯誤信息,包括:
Port: Could not establish connection. Receiving end does not exist.
但我並不在catch語句結束。
閱讀的價值['chrome.runtime.lastError'(https://developer.chrome.com/extensions/runtime.html#property-lastError)找出是否發生錯誤。 –
@RobW:在這種情況下似乎沒有定義。實際上有些奇怪的事情正在發生,因爲每次跟蹤調試器中的代碼時都會看到不一致的catch事件。這是一種異步魔法嗎? – stsquad
插入一個'debugger;'語句來查明。 –