5

在 Google Chrome 扩展程序中,我想在内容脚本和弹出页面之间传递消息。我还希望在弹出页面向内容脚本发送执行此操作的信号时触发内容脚本中的一个函数。

Google Chrome 扩展开发者文档中的消息部分指出,消息可以“从您的内容脚本传递到扩展页面,反之亦然”(引自http://code.google.com/chrome/extensions/messaging. html )

这是否意味着我可以在内容脚本和弹出页面之间发送/接收消息?因为我看到的用法是用于后台页面和内容脚本之间的通信。

或者我是否必须设置一个 3 路消息传递路线 - 即。内容脚本 <--> 背景页面 <--> 弹出页面。如果是这种情况,我如何在后台页面 <--> 弹出页面之间设置消息传递?

在从弹出页面向内容脚本发送信号后,如何在内容脚本中触发函数?这是否也需要存在后台脚本?

4

1 回答 1

12

内容脚本只能向后台页面发送消息。如果要将消息从内容脚本发送到弹出窗口,则必须:

  1. 将消息从内容脚本发送到后台页面。

    chrome.runtime.sendMessage( ...message... , function() { /*response*/ });
    
  2. 在后台接收消息。

    chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { ... });
    
  3. 将消息传递到弹出窗口。要获取window对弹出窗口的全局对象的引用,请使用chrome.extension.getViews. 注意:与大多数其他 chrome API 不同,此方法是同步的:

    var popupWindows = chrome.extension.getViews({type:'popup'});
    if (popupWindows.length) { // A popup has been found
        // details is the object from the onMessage event (see 2)
        popupWindows[0].whatever(message, sendResponse);
    }
    
  4. 在弹出窗口中,定义whatever方法。

    function whatever(message, sendResponse) {
        // Do something, for example, sending the message back
        sendResponse(message);
    }
    
  5. sendResponse(4) 被调用时,details.sendResponse(参见 3) 被调用。这反过来function() { /*response*/ }又从 1 调用。

注意:chrome.runtime.sendMessage/onMessage仅在 Chrome 26+ 中受支持。chrome.extension.sendMessage如果您还想支持旧版浏览器,请使用。

于 2012-07-23T17:49:38.287 回答