Chrome扩展程序:chrome.storage不会保存任何内容

时间:2014-04-25 12:17:56

标签: javascript google-chrome google-chrome-extension

我即将写一个用于计算在线时间的扩展程序。 manifest.json文件中的权限:

"permissions": [
"tabs",
"<all_urls>",
"storage",
 "cookies"
],

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

console.log(values)只给我一个&#34; []&#34 ;;开发人员工具在资源中没有显示任何内容 - &gt;本地存储,在控制台中都不是错误。

我做错了什么?

由于

1 个答案:

答案 0 :(得分:5)

  

我做错了什么?

有几件事。

首先,您滥用JavaScript数组。如果您将firstValues记录到控制台,则[]JSON.parse(undefined)(尽管它仍保留数据)。你需要一个Object来拥有命名键,Arrays用数字索引。

其次,如果我尝试运行该代码,我会遇到JSON.parse是一个例外的事实(因为它不是有效的JSON)。所以你需要检查一下,或者更好的是,每当做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}); } }); 不同。

所以,你的代码看起来应该是这样的:

chrome.storage

最后,看看Resources&gt;本地存储不会向您显示localStorage的内容,它会显示chrome.storage。据我所知,chrome.storage未在DevTools中表示。

为方便起见,这里是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"); } } 的记录器:

{{1}}
相关问题