2013-08-06 24 views
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语句结束。

+1

阅读的价值['chrome.runtime.lastError'(https://developer.chrome.com/extensions/runtime.html#property-lastError)找出是否发生错误。 –

+0

@RobW:在这种情况下似乎没有定义。实际上有些奇怪的事情正在发生,因为每次跟踪调试器中的代码时都会看到不一致的catch事件。这是一种异步魔法吗? – stsquad

+0

插入一个'debugger;'语句来查明。 –

回答

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"); 
     } 
    }); 
}); 
相关问题