google-chrome-extensionundefinedgoogle-chrome-storage

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


I am working on a Google Extension and using Google Storage.

Below is my code for saving and accessing the saved data. I checked the console and the data is saving correctly. However, when I access this data using chrome.storage.local.get console returns undefined for the value and not the value saved.

Code for Saving: save.js for popup.html

function save() {
    # the id is for a textarea in another html page
    var text = document.getElementById("text").value;

    chrome.storage.sync.set({"txt": text}, function(){
      
       # console states the correct value
       console.log('Value is set to ' + text);
     });

   # this is the page I want to retrieve the saved data in 
   window.location.replace("anotherHTMLpage.html");

}

Code for Accessing: retrieve.js for anotherHTMLpage.html

function retrieve() {
    chrome.storage.sync.get(["txt"], function(data) {
     
      # console says "value currently is undefined"
      console.log('Value currently is ' + data.key);

   });
  }

Thanks for the help in advance!


Solution

  • 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