【问题标题】:Message passing between content scripts and background page内容脚本和后台页面之间的消息传递
【发布时间】:2013-08-18 16:04:26
【问题描述】:

我已将内容脚本注入所有帧。我从后台发送了一个请求,并希望收到来自所有内容脚本(已注入的帧)的响应。

目前我只能收到一个响应,如何接收所有内容脚本的响应?

内容脚本:

chrome.runtime.onMessage.addListener(   
  function(request, sender, sendResponse) { 
    if (request.bgReq == "windowInfo")
    alert("bgreq received : "+ window.location.host);

});

后台脚本:

chrome.runtime.onMessage.addListener(function(sentWords) {
    if (sentWords.words == "injection") {
        //send request to content scritps
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            chrome.tabs.sendMessage(tabs[0].id, {bgReq:"windowInfo"});
        });
    }
});

【问题讨论】:

    标签: javascript google-chrome google-chrome-extension message


    【解决方案1】:

    您需要将其显式发送到所有窗口中的所有选项卡:

    chrome.windows.getAll({},function(windows){
      for( var win in windows ){
        chrome.tabs.getAllInWindow(win.id, function(tabs) {
          for (var i in tabs) {
            chrome.tabs.sendMessage(tabs[0].id, {bgReq:"windowInfo"});
          }
        });
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-15
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      相关资源
      最近更新 更多