Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 645
shuboy2014 Avatar asked Jul 08 '16 07:07

shuboy2014


People also ask

How do I check Chrome storage data?

With the extension's background page open, just go to the developer tools by pressing F12, then go to the Application tab. In the Storage section expand Local Storage. After that, you'll see all your browser's local storage there.

How do I find local storage value in Chrome?

# View localStorage keys and valuesClick the Application tab to open the Application panel. Expand the Local Storage menu. Click a domain to view its key-value pairs. Click a row of the table to view the value in the viewer below the table.

Does Chrome sync local storage?

sync , the stored data will automatically be synced to any Chrome browser that the user is logged into, provided the user has sync enabled. When Chrome is offline, Chrome stores the data locally. The next time the browser is online, Chrome syncs the data. Even if a user disables syncing, storage.


1 Answers

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.

like image 80
Xan Avatar answered Oct 07 '22 18:10

Xan