Reputation: 51
I am writing an app that starts by instantiating some blank starter data for a graph into the chrome.storage, as the extension is being used the data is updated.
The way I formatted the code right now is that the storage is instantiated when the code starts, which is a problem because the code starts over when you restart chrome so it overwrites all the data that has been written.
So I think I need to write in some sort of checking function where I can write something like
chrome.storage.sync.get("data", function (result){
if ("data" !== null){
initStorage();
} else {
//do stuff
}
})
Is this the correct way to go about fixing this issue? I'm wondering if this works with how the storage functions? Does each extension have it's own storage area so there won't be anything there if I haven't saved anything yet?
Upvotes: 1
Views: 95
Reputation: 77523
Note that you can provide default values in get
:
var default_data = { /* something */ };
chrome.storage.sync.get({data: default_data}, function(result) {
// If "data" wasn't present in storage, result.data is a copy of default_data
// Otherwise, result.data is a copy of the actual stored value
chrome.storage.sync.set(result); // To save the default, if not saved
});
Upvotes: 3
Reputation: 1857
Because you can retrieve multiple values from storage, result
is an object with the keys you requested. Check if "data" exists in that object:
chrome.storage.sync.get("data", function(result) {
if (!("data" in result)) {
initStorage();
}
// Do stuff
});
Upvotes: 1