Chrome消息从后台到内容脚本再到后台
chrome messaging from background to content script to background again
所以我试图将数据从chrome背景页面的本地存储发送到内容脚本,然后对数据进行一些操作。之后,我想将其发送回后台页面并更新后台页面的本地存储。这可能吗?我知道如何将数据从后台发送到内容脚本,但是如何从内容脚本发送到后台呢?
background.html
var background = chrome.extension.getBackgroundPage();
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse, getBackResponse) {
if (request.extensionSettings === "storage") {
// send local storage data {"one": "data", "two": "data"}
sendResponse({storageString: background.localStorage.extdata});
// save new data from content script
localStorage.setItem("extdata", getBackResponse);
}
});
script.js
chrome.runtime.sendMessage({extensionSettings: "storage"}, function(response) {
var json = JSON.parse(response.storageString);
console.log(json);
// take json object do a few things with data
// take data and make new json string, and send it background page
sendBack('{"one": "new data", "two": "more new data"}');
});
好的,在这种情况下,你只是想区分你发送到背景页面的消息。一种方法是使用像这样的简单标识符:
内容脚本chrome.runtime.sendMessage({method:"getStorage",extensionSettings:"storage"},
function(response) {
var json = JSON.parse(response.storageString);
console.log(json);
// take json object do a few things with data
// take data and make new json string, and send it background page
// Let's just say that `sendBack` is now defined to be a var
// With the info you want to send back
var sendBack = {"one": "new data", "two": "more new data"};
chrome.runtime.sendMessage({method:"setStorage", newData:sendBack});
});
有了这个,我们发送一个消息来获取数据,在回调中操作它,然后发送它回来。现在来处理它。
背景页
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
if(message.method == "getStorage"){
if(message.extensionSettings === "storage") {
// send local storage data {"one": "data", "two": "data"}
sendResponse({storageString: background.localStorage.extdata});
}
}
else if(message.method == "setStorage"){
// save new data from content script
localStorage.setItem("extdata", message.newData);
}
});
通过这种方式,我们可以处理各种不同类型的消息,只需改变method
的值或您想要的任何名称
相关文章:
- 选项卡侦听器未被来自后台脚本的消息激活
- 使用javascript后台脚本获取Yotutube频道信息
- 在chrome web商店中打开时,是否有允许执行内容/后台脚本的解决方案
- 使用chrome扩展,如何使用长寿命连接(端口)将消息从后台脚本传递到内容脚本
- 为什么chrome.sockets.tcp.create()在应用程序后台脚本中不起作用
- 后台脚本在受限范围内运行的 Chrome 应用
- Chrome:同时使用内容和后台脚本不起作用
- 从“选项”弹出窗口中选择一个值,然后将其保存到 Chrome.storage,以便在后台脚本中用作值
- 应用程序后台脚本,访问打开的窗口的元素
- Chrome 扩展程序:无法让消息传递在后台脚本和内容脚本之间正常工作
- npm 后台脚本去哪儿了
- 为什么我的Google扩展似乎只有在我'我正在观察后台脚本控制台
- 后台脚本中的setIntegal
- 在非持久性后台脚本上添加上下文菜单项
- 正在将消息发送到后台脚本
- 多次加载后台脚本
- Chrome扩展如何获得后台脚本将被关闭的通知
- chrome扩展的浏览器操作、后台脚本和内容脚本之间通信的上下文和方法
- Chrome扩展:错误时发送消息从注入脚本回后台脚本
- 在弹出框中从iframe发送消息到后台脚本