Javascript 如何使用Chrome.Storage?
我需要保存扩展的状态。如果启用,代码将在特定网站上运行,如果未启用,则不会运行 我还不知道怎么做,因为我还没有完全理解 这是复选框(popup.html)的html:Javascript 如何使用Chrome.Storage?,javascript,jquery,html,google-chrome,google-chrome-extension,Javascript,Jquery,Html,Google Chrome,Google Chrome Extension,我需要保存扩展的状态。如果启用,代码将在特定网站上运行,如果未启用,则不会运行 我还不知道怎么做,因为我还没有完全理解 这是复选框(popup.html)的html: 关 这是jQuery代码,当您单击按钮(bg颜色、开/关文本)时,它只会更改颜色和文本。此代码位于popup.js中: if ($("#checkbox").is(":checked")) { $("#onOroff").text("OFF"); $(".slider").css({ "back
关
这是jQuery代码,当您单击按钮(bg颜色、开/关文本)时,它只会更改颜色和文本。此代码位于popup.js中:
if ($("#checkbox").is(":checked")) {
$("#onOroff").text("OFF");
$(".slider").css({ "background-color": "#C75052" });
} else {
$("#onOroff").text("ON");
$(".slider").css({ "background-color": "#50c878" });
}
});
在这里您可以看到扩展:
删除广告的代码位于contentEditor.js中
当你点击扩展并打开它时,Chrome将其视为另一个正在打开的页面,因此当我打开扩展(点击关闭)并关闭扩展窗口时,重新打开它,它不会保存该状态
我想我需要将check/unchecked保存在一个变量中,将其传递到chrome.Storage,并让chrome.Storage保存按钮的最新版本。您需要在清单中声明存储权限
{
"name": "My extension",
...
"permissions": [
"storage"
],
...
}
然后像这样使用它
chrome.storage.sync.set({yourValue: true}, function(){});
设置它,并获得它
chrome.storage.sync.get(['yourValue'], function(result){
// your value is in result.yourValue
});
第二个参数(函数)是回调,您需要使用它来指示下一步如何处理该数据。在manifest.json中声明权限后
{
"name": "My extension",
...
"permissions": [
"storage"
],
...
}
您可以在内容、背景和弹出脚本中使用chrome.storage API
if ($("#checkbox").is(":checked")) {
$("#onOroff").text("OFF");
chrome.storage.local.set({button: 'off'}, function() {
console.log('Button state saved to off');
});
$(".slider").css({ "background-color": "#C75052" });
} else {
$("#onOroff").text("ON");
chrome.storage.local.set({button: 'on'}, function() {
console.log('Button state saved to on');
});
$(".slider").css({ "background-color": "#50c878" });
}});
然后,您可以从chrome.storage请求background.js文件中的值
chrome.storage.local.get(['button'], function(result) {
console.log('The button's state is currently ' + result.key);
});
扩展由不同的上下文/组件组成,因此了解代码的具体运行位置非常重要。添加manifest.json并描述哪些文件包含发布的代码。至于使用
chrome.storage
很容易找到现有的例子,比如,这里有一个随机的例子:.Jquery在popup.js中,html代码称为popup.html。我在后台脚本中没有任何内容,编辑页面内容的代码在contentEditor中。我很难分析我需要做什么。我是否在popup.js中写入chrome.storage.set?如果是,背景脚本将如何读取它?它们在不同的范围内。我在任务中声明了存储。问题是:我有三个脚本:Popup.js、contentEditor.js和background.js。我不知道如何实际存储复选框的值(在哪个脚本中)以及如何保存它。因为我怀疑后台脚本能否读取popup.html的css。