从内容脚本发送数组到背景页面 [英] Sending an array from a content script to the background page

查看:89
本文介绍了从内容脚本发送数组到背景页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的内容脚本发送一个数组到后台页面,以便稍后使用chrome.extension.getBackgroundPage()从弹出窗口中存储和调用它。



目前,我的背景页面看起来像这样(基于来自开发者网站的示例)。

  < HTML> 
< head>
< script>

函数onRequest(request,sender,sendResponse){

chrome.pageAction.show(sender.tab.id);
sendResponse({});
};

chrome.extension.onRequest.addListener(onRequest);

< / script>
< / head>
< / html>

我的内容脚本执行一些简单的正则表达式,并且如果它发现匹配响应:

  chrome.extension.sendRequest({},function(response){}); 

我想要做的是将内容脚本创建的数组发送回后台页面。对于如何解决这个问题,我有点难过。我需要创建第二个请求,还是可以将数组与上面的响应一起发送。



谢谢大家的帮助。这是我第一次在这里发帖,尽管我很长时间从其他人发布的问题和答案中受益):

假设您的匹配数组称为匹配,您的内容脚本可以使用类似以下内容:

  chrome.extension.sendRequest({matches:matches},function(response){}); 

然后在您的背景页面中,您可以从请求中提取匹配数组:

函数onRequest(request,sender,sendResponse){
var matches = request.matches;
//在这里使用matches数组做
sendResponse({});
};

通常,无论您放入请求的数据参数 chrome.extension.sendRequest 将传递给您的 onRequest 函数。有关更多详细信息,请参阅消息传递的扩展文档。


I want to send an array from my content script to the background page, so that it can be stored and called upon later from the popup using chrome.extension.getBackgroundPage().

At the moment, my background page looks like this (based on an example from the developer website).

<html>
<head>
    <script>

      function onRequest(request, sender, sendResponse) {

        chrome.pageAction.show(sender.tab.id);
        sendResponse({});
      };

      chrome.extension.onRequest.addListener(onRequest);

    </script>
  </head>
</html>

My content script performs a few simple regexes, and if it finds a match responds with:

chrome.extension.sendRequest({}, function(response) {});

What I would like to do is send an array created by the content script back to the background page. I'm somewhat stumped as to how to go about this. Do I need to create a second request, or can I send the array along with the response above.

Thank you all for your help. This is my first time posting here, though I've long benefited from the questions and answers posted by others :)

解决方案

Assuming your array of matches is called matches, your content script could use something like:

chrome.extension.sendRequest({matches: matches}, function(response) {});

Then in your background page, you can extract the matches array from the request:

function onRequest(request, sender, sendResponse) {
  var matches = request.matches;
  // do stuff with the matches array here
  sendResponse({});
};

Generally, whatever data you put into the request argument of chrome.extension.sendRequest will be passed to your onRequest function. See the extension documentation about message passing for more details.

这篇关于从内容脚本发送数组到背景页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆