Firstly, since chrome.storage is asynchronous, everything has to be done in a callback - you cannot if...else outside because nothing will be returned (for now). Regardless of whether Chrome responds to the request, it moves to the callback as a dictionary of key values (even if you asked for only one key).
So,
chrome.storage.sync.get('links', function(data) { if (/* condition */) { // if already set it then nothing to do } else { // if not set then set it } // You will know here which branch was taken }); // You will not know here which branch will be taken - it did not happen yet
There is no difference between undefined and not in storage. So you can check this:
chrome.storage.sync.get('links', function(data) { if (typeof data.links === 'undefined') { // if already set it then nothing to do } else { // if not set then set it } });
However, chrome.storage has a better scheme for this operation. You can specify the default get() value:
var defaultValue = "In case it not set yet"; chrome.storage.sync.get({links: defaultValue}, function(data) {
A good place to set defaults will be at startup; chrome.runtime.onStartup and / or chrome.runtime.onInstalled events on the background page / events are best suited.
Xan
source share