Search code examples
javascriptgoogle-chromegoogle-chrome-extensionstoragegoogle-chrome-app

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


For some reason my getStorageKeyValue method returns undefined instead of the value previously set. I am beating my head over this for approximately 3 days now. The google searches didn't solve my problem and I beg you please help! How to fix this?

This is my current JavaScript code:

// Sets a key and stores its value into the storage
function setStorageKey(key, value){
    chrome.storage.sync.set({ key: value });
}

// Gets a key value from the storage
function getStorageKeyValue(key){
    chrome.storage.sync.get([key], function(result) {
        return result.key;
    });
}

// Set a new key inside the storage
let value = 10;
setStorageKey("K1", value);

// Get the value of the key passed in parameter from the storage
let receivedValue = getStorageKeyValue("K1");

alert("Set value: "+value+" --- Received value: "+receivedValue);
// Results in: Set value: 10 --- Received Value: undefined

Solution Found:

// Sets a key and stores its value into the storage
function setStorageKey(key, value){
    chrome.storage.sync.set({ [key]: value });
}

// Gets a key value from the storage
function getStorageKeyValue(key, onGetStorageKeyValue){
    chrome.storage.sync.get([key], function(result) {
       onGetStorageKeyValue(result[key]);
    });
}

// Running our code to see the result:
// 1) Set value & Save it to storage
let value = 10;
setStorageKey("K1", value);

//) 2) Get saved value from storage and display a warning message with the value
getStorageKeyValue("K1", function(key) {
  alert("Set value: "+value+" --- Received value: "+ key);
});
// Results in: Set value: 10 --- Received Value: 10

Many thanks for your responses and help. I hope that this question will be useful for other developers.

Special thanks to: johannchopin and Andreas. Their responses helped me to solve my issue.


Solution

  • 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);
    });