javascriptgoogle-chromegoogle-chrome-extensiongoogle-chrome-devtoolsgoogle-chrome-storage

Unable to get array from chrome.storage


Whenever I try to get data from chrome.storage, it returns undefined.

chrome.storage.sync.get('courses', function(result) {
      currentCourses = result.courses
      console.log(currentCourses)
      currentCourses.push(coursename)
      chrome.storage.sync.set({courses: currentCourses}, function() {
        alert(`Course "${coursename}" has been added !`)
      });
}
userCourses = async () => {
  await chrome.storage.sync.get('courses', function(result) {
      return(result.courses)
  });
}
courseData = userCourses()
console.log(courseData)

I found an answer here on stack overflow, but it is giving the same error. I am new to JS, and not comfortable with Promises.

I tried the example from the official docs, but it is also giving the same error as below. Can someone help me with a solution, or modify my code ? Error


Solution

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