在发送端:即来自内容脚本。
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>
在接收端:即在后台脚本中。*
背景.js:
chrome.runtime.onMessage.addListener(function(MessageSender sender, function
sendResponse){
/* 2) what should be here */ });
3)在这里,我如何收集(存储)从 contentscript 传递的数组变量。
4)现在,我可以从background.js直接调用popup.js中的任何函数(脚本文件
链接到 popup.html)。
有人可以回答以上4个问题吗?
提前致谢!
检查我的弹出窗口,出现以下错误:
最佳答案
在manifest.json
添加存储权限
"permissions": ["storage"]
在 contentscript.js
将您的数据保存在本地存储 Google Chrome 中:Chrome Storage API
var data = ''; //set your data here
chrome.storage.local.set({
'myVariable': data
});
使用sendMessage调用后台页面:Chrome messaging API
chrome.runtime.sendMessage({
greeting: "myAction"
});
在background.js
从 contentscript.js 获取消息
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.greeting == "myAction") {
collectData();
}
});
定义collectData()函数
function collectData() {
chrome.storage.local.get('myVariable', function (items) {
console.log(items); //your data is on items.myVariable
});
}
使用消息API从background.js调用popup.js函数
关于javascript - 内容脚本、后台脚本和弹出脚本之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22477645/