wer*_*her 2 javascript google-chrome google-chrome-extension
我打算写一个扩展计算我的在线时间.manifest.json文件中的权限:
"permissions": [
"tabs",
"<all_urls>",
"storage",
"cookies"
],
Run Code Online (Sandbox Code Playgroud)
background.js:
var firstValues = new Array(); //first extension startup values
firstValues["tag"] = "0";
firstValues["gesamt"] = "0";
var values = new Array();
chrome.storage.local.get('values', function (result) {
values = JSON.parse(result.values); //Saving the values in the "values" array
console.log(values);
if (!values.length >0) chrome.storage.local.set({'values': JSON.stringify(firstValues)});
}); //Setting values to zero, if it is the first start
Run Code Online (Sandbox Code Playgroud)
console.log(values)只给我一个"[]"; Developer Tool在资源 - >本地存储中没有显示任何内容,控制台中也没有错误.
我究竟做错了什么?
谢谢
我究竟做错了什么?
好几件事.
首先,您滥用JavaScript数组.您firstValues
,如果您登录它安慰,是[]
(虽然它仍然保存的数据).您需要一个Object来拥有命名键,Arrays由数字索引.
其次,如果我尝试运行该代码,我会遇到JSON.parse(undefined)
一个异常的事实(因为它不是有效的JSON).所以你需要检查它,或者更好的是,每当做的时候都要做异常处理JSON.parse
.
但更好的方法是不要尝试自己序列化,因为chrome.storage
文档告诉你它是自动完成的.与之不同localStorage
,您可以存储对象和检索对象.
所以,你的代码应该是这样的:
//first extension startup values
var firstValues = { tag : 0, gesamt : 0 }; // Nothing wrong with literals
chrome.storage.local.get('values', function (result) {
if(result.values) { // defined
console.log(result.values);
} else { // uninitialised
chrome.storage.local.set({values: firstValues});
}
});
Run Code Online (Sandbox Code Playgroud)
最后,查看资源>本地存储将不会显示其内容chrome.storage
,它显示localStorage
.据我所知,chrome.storage
DevTools中没有代表.
为方便起见,这里有一个记录器chrome.storage
:
function logStorage() {
if(chrome.storage) {
chrome.storage.local.get(function(data){
console.log("chrome.storage.local:");
if(chrome.runtime.lastError) {
console.error(chrome.runtime.lastError);
} else {
console.log(data);
}
chrome.storage.sync.get(function(data){
console.log("chrome.storage.sync:");
if(chrome.runtime.lastError) {
console.error(chrome.runtime.lastError);
} else {
console.log(data);
}
});
});
} else {
console.warn("chrome.storage is not accessible, check permissions");
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1388 次 |
最近记录: |