内容,背景和弹出脚本之间的通信 [英] Communication between contentscript, background and popup scripts
问题描述
<脚本>
//一些DOM代码来获取值以存储在'标记'数组中。
//这里我将标记数组发送到background.js。
// 1)我发送它的权利?
chrome.runtime.sendMessage(marks);
< / script>
接收结束时:即在后台脚本中。*
background.js:
$ b
chrome.runtime.onMessage.addListener(function(MessageSender发件人,函数
sendResponse){
/ * 2)这里应该是什么* /});
3)在这里,我如何收集(存储)从contentscript传递的数组变量。
4)现在,我可以直接调用popup.js中的任何函数(脚本文件
链接到popup.html)。
任何人都可以回答上述4个问题吗?
在此先感谢!
检查我的弹出窗口,给了我下面的错误信息:
添加存储权限
permissions:[storage]
in contentscript.js
将您的数据保存到本地存储Google Chrome: Chrome存储API
var data =''; //在这里设置你的数据
chrome.storage.local.set({
'myVariable':data
});
使用sendMessage调用背景页面: Chrome消息API
chrome.runtime.sendMessage ({
greeting:myAction
});
in background.js
从contentscript.js获取消息
chrome.runtime.onMessage.addListener(
function请求,发件人,sendResponse){
if(request.greeting ==myAction){
collectData();
}
});
定义collectData()函数
function collectData(){
chrome.storage.local.get('myVariable',function(items){
console.log(items); // your data在items.myVariable
});
}
从background.js中调用popup.js函数使用消息传递API
On sending side : i.e from contentscript.
contentscript.js:
<script>
//some DOM code to obtain values to store in 'marks' array.
//here I'm sending marks array to background.js.
// 1) Am I sending it right?
chrome.runtime.sendMessage(marks);
</script>
On receiving end : i.e in background script.*
background.js:
chrome.runtime.onMessage.addListener(function(MessageSender sender, function
sendResponse){
/* 2) what should be here */ });
3) here , how can I collect(store) the array variable passed from contentscript.
4) Now,from background.js can I directly call any function in popup.js(script file
linked to popup.html).
Can anyone please answer the above 4 questions?
Thanks in advance!
Inspecting my popup,gave me following error :
in manifest.json
add storage permission
"permissions": ["storage"]
in contentscript.js
save your data in the local storage Google Chrome : Chrome Storage API
var data = ''; //set your data here
chrome.storage.local.set({
'myVariable': data
});
use sendMessage to call the background page : Chrome messaging API
chrome.runtime.sendMessage({
greeting: "myAction"
});
in background.js
get the message from contentscript.js
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.greeting == "myAction") {
collectData();
}
});
define the collectData() function
function collectData() {
chrome.storage.local.get('myVariable', function (items) {
console.log(items); //your data is on items.myVariable
});
}
to call popup.js function from background.js use the messaging API
这篇关于内容,背景和弹出脚本之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!