【问题标题】:Google Chrome Extension- Messages + call to function between popup page and content scriptGoogle Chrome 扩展 - 消息 + 调用弹出页面和内容脚本之间的功能
【发布时间】:2012-07-23 17:23:35
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: google-chrome-extension


    【解决方案1】:

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

    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)被调用。这反过来又从 1 调用 function() { /*response*/ }。

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

    【讨论】:

    猜你喜欢
    • 2018-08-15
    • 1970-01-01
    • 2011-08-31
    • 2017-12-24
    • 2019-11-05
    • 2013-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多