What am I doing wrong?
Several things.
First, you are misusing JavaScript arrays. Your firstValues
, if you log it to console, is []
(though it still holds the data). You need an Object to have named keys, Arrays are indexed by numbers.
Second, if I try to run that code, I run into the fact that JSON.parse(undefined)
is an exception (since it's not valid JSON). So you need to either check for that or, even better, do exception handling whenever doing JSON.parse
.
But even better would be to not try to serialize things yourself, as chrome.storage
docs tell you that it is done automagically. You can store objects and retrieve objects, unlike localStorage
.
So, your code should look something like that:
//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});
}
});
Lastly, looking at Resources > Local Storage will not show you the contents of chrome.storage
, it shows localStorage
. As far as I am aware, chrome.storage
is not represented in DevTools.
For convenience, here's a logger for 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");
}
}