0

我正在尝试扩展我的后台进程和内容脚本之间的一些消息处理。在正常情况下,我的后台进程通过 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.

但我并没有在 catch 语句中结束。

4

1 回答 1

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");
        }
    });
});
于 2013-08-08T17:51:17.897 回答