简体   繁体   English

在内容脚本和后台页面之间传递消息

[英]Message passing between content scripts and background page

I have injected content scripts to all frames. 我已将内容脚本注入所有框架。 I sent a request from background and would like to receive response from all the content scripts (frames that have been injected). 我从后台发送了一个请求,希望收到所有内容脚本(已注入的帧)的响应。

Currently I can only receive one response, how do I receive responses from all content scripts? 目前,我只能收到一个回复​​,如何接收所有内容脚本的回复?

content script: 内容脚本:

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

});

background script: 后台脚本:

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"});
        });
    }
});

You need to explicitly send it to all tabs in all the windows : 您需要将其显式发送到所有窗口的所有选项卡中:

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"});
      }
    });
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 两个内容脚本之间传递的消息(通过后台) - Message passing between two content scripts (through background) 邮件从内容脚本传递到Chrome扩展程序中的后台页面 - Message Passing from Content Scripts to Background Page in Chrome Extensions 是否可以在不使用后台脚本的情况下在多个内容脚本之间传递消息? - Is message passing between multiple content scripts possible without using the background script? Chrome扩展程序消息在内容和背景之间传递 - Chrome extension message passing between content and background 在可信页面内容和插件之间传递消息 - Message passing between trusted page content and addon 是否有像32bytes或64Bytes这样的大小限制? 在内容脚本和chrome扩展的后台页面之间传递消息? - Is there a size limit like 32bytes or 64Bytes? for message passing between content scripts and background pages for chrome extensions? 在2个插件脚本之间传递消息 - Passing message between 2 addon scripts 内容和背景之间传递的Chrome扩展程序消息无效 - Chrome extension message passing between content and background not working Chrome 扩展消息在后台和内容脚本之间传递 - Chrome Extension Message Passing between background and content script 消息未在内容广告背景脚本文件之间传递 - Message not passing between content ad background script file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM