shuboy2014
shuboy2014

Reputation: 1370

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

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

Example:
I want to check the key 'links':

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 will be appreciated.

Upvotes: 24

Views: 9586

Answers (1)

Xan
Xan

Reputation: 77482

First off, since chrome.storage is asynchronous, everything has to be done in the callback - you can't if...else outside, because nothing will be returned (yet). Whatever Chrome answers to the query it passes to the callback as a key-value dictionary (even if you only asked for 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 distinction between the value undefined and not being in storage. So you can test for that:

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 
  }
});

That said, chrome.storage has a better pattern for this operation. You can provide a default value to get():

var defaultValue = "In case it's 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 would be at startup; chrome.runtime.onStartup and/or chrome.runtime.onInstalled events in a background/event page fit best.

Upvotes: 38

Related Questions