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.
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.
# 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With