Initially, due to the asynchronous nature of chrome.storage
, all operations must be carried out within the callback function. It is not possible to use an if...else
statement outside of the callback since no data will be returned at that point. Chrome responds to queries by passing a key-value dictionary to the callback, even when only requesting one key.
Therefore,
chrome.storage.sync.get('links', function(data) {
if (/* condition */) {
// do nothing if already set
} else {
// set the value if not already set
}
// You can determine which branch was executed here
});
// It is unknown at this point which branch will be executed - it has not occurred yet
There is no distinction between the value undefined
and being absent in storage. To account for this, you can check as follows:
chrome.storage.sync.get('links', function(data) {
if (typeof data.links === 'undefined') {
// do nothing if already set
} else {
// set the value if not already set
}
});
On another note, chrome.storage
offers a more convenient pattern for handling such scenarios. By specifying a default value in the get()
method:
var defaultValue = "Default if unset";
chrome.storage.sync.get({links: defaultValue}, function(data) {
// data.links will contain either the stored value or the default if not set
chrome.storage.sync.set({links: data.links}, function() {
// The value is now stored, eliminating the need for repetition
});
});
It is recommended to establish defaults during startup; events like chrome.runtime.onStartup
and/or chrome.runtime.onInstalled
in a background/event page are suitable for this purpose.