Returning Chrome Storage API Value Without Function

How to wait for asynchronous chrome.storage.local.get() to finish before continuing execution

You need to wait for both callback function that you pass to chrome.storage.local.get(..) to be executed before you call continueCode(), also, you can check both storage properties with a single call, here is an example:

function getData() {
chrome.storage.local.get(['key', 'key2'], function(result) {
if (typeof result.key !== 'undefined') {
object1.innerHTML = result.key.val;
}
if (typeof result.key2 !== 'undefined') {
object2.innerHTML = result.key2.val;
}
continueCode();
}
}

Why does chrome.storage.local.get return undefined for the value?

Chrome saves the data under the key you set it as. In your example, you saved it as txt, so it will be under data.txt not data.key.

Check out the docs for some more details https://developer.chrome.com/docs/extensions/reference/storage/#usage

Chrome Extension - Chrome.storage - Why does chrome.storage.sync.get returns undefined?

chrome.storage.sync.get is an asynchronous method, that's why you need to give a callback to it when it has done getting the storage. So you can't adopt a procedural code structure for that. A solution would be to use a callback structure:

function setStorageKey(key, value){
chrome.storage.sync.set({ key: value });
}

function getStorageKeyValue(key, onGetStorageKeyValue){
chrome.storage.sync.get([key], function(result) {
onGetStorageKeyValue(result.key);
});
}

let value = 10;
setStorageKey("K1", value);

getStorageKeyValue("K1", function(key) {
alert("Set value: "+value+" --- Received value: "+ key);
});

Unable to get array from chrome.storage

Wrap the call to storage in a promise and await it:

function getStorageValuePromise(key) {
return new Promise((resolve) => {
chrome.storage.sync.get(key, resolve);
});
}

await getStorageValuePromise('val');


Related Topics



Leave a reply



Submit