所以我试图将数据从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"}');
});
答案 0 :(得分:2)
好的,在这种情况下,您只想区分发送到后台页面的消息。一种方法是使用这样的简单标识符:
内容脚本
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
的值或您想要命名的任何内容来处理各种不同类型的消息。