I am trying to make a javascript method to load multiple simple settings from the browser local storage.
Currently I have the following code which work, but it quickly get unpractical and lengthy to load multiple settings ( I only provided 2 for this example ):
const readLocalStorage = async (key) => {
return new Promise((resolve, reject) => {
chrome.storage.local.get([key], function (result) {
if (result[key] === undefined) {
reject();
} else {
resolve(result[key]);
}
});
});
};
function somefunction(){
await readLocalStorage('settingsSelfDiscard')
.then(function(result) {
if(result == true || result == false){
selfDiscard = result;
}
})
.catch((err) => {
//Can't retreive the key, probably non-existent
});
await readLocalStorage('settingsCompactToolbar')
.then(function(result) {
if(result == true || result == false){
compactToolbar = result;
}
})
.catch((err) => {
//Can't retreive the key, probably non-existent
});
}
I would like a method which I can use like, or similar to this:
selfDiscard = loadLocalStorage("settingsSelfDiscard");
compactToolbar = loadLocalStorage("settingsCompactToolbar");
And just get null if it's non-existent.
Since the API is asynchronous you can't use it without
awaitorthen, but you can get multiple keys in one call by providing an array toget, see the documentation. BTW in ManifestV3 the API is already promisified: