How to check if a key is installed in chrome.storage?

I am doing a Google Chrome extension and I want to check if the key is installed or not in chrome.storage.sync .

An example :
I want to check the 'links' key:

 if (chrome.storage.sync.get('links',function(){ // if already set it then nothing to do })); else{ // if not set then set it } 

Any helpful suggestion would be appreciated.

+7
javascript google-chrome-extension
source share
1 answer

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) { // data.links will be either the stored value, or defaultValue if nothing is set chrome.storage.sync.set({links: data.links}, function() { // The value is now stored, so you don't have to do this again }); }); 

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.

+8
source share

All Articles