Saving an array to local storage

I am new to WebExtensions and JavaScript. I am trying to write a small extension with a button pageAction

that just saves the current url to local storage when clicked (ie Some very simple "favorite" function). However, I am having problems using chrome.storage.local.set()

and .get()

. I searched for the code in this question and this question to try and use it for my purposes but failed. This is what I mean now.

The function saveURL()

is supposed to load the array into local storage, update it with the new url, and save it back to local storage (at the moment I just have a dud line that I am trying to push this array).

async function saveURL() {
  console.log("Save URL called.");
  var urls = await loadURLs();
  console.log(urls);
  urls.push("a-new-url")
  console.log(urls);
  chrome.storage.local.set({'pearsurls': urls});
  urls = await loadURLs();
  console.log(urls);
  return true;
}

      

The function loadURLs()

should fetch data from local storage. I am using the default in storage.local.get()

to initialize the array on first use.

function loadURLs(){
  var pearsurls = []
  console.log("Loading all saved URLs");
  chrome.storage.local.get({pearsurls: []}, function (result) {
    pearsurls = result.pearsurls;
    console.log(pearsurls)
  });
  console.log(pearsurls)
  return pearsurls;
}

      

The output in the console gives me:

Save page  save.js:52:3
Save URL called.  save.js:5:3
Loading all saved URLs  save.js:38:3
Array [  ]  save.js:43:3
Array [  ]  save.js:7:3
Array [ "a-new-url" ]  save.js:9:3
Loading all saved URLs  save.js:38:3
Array [  ]  save.js:43:3
Array [  ]

      

those. my function loadURLs()

doesn't seem to do anything ... What am I doing wrong?

+3


source to share


1 answer


The function is loadURLs

not async

or returns Promise

, so it ends up immediately with an empty array.

Try this instead:



function loadURLs(){
  console.log("Loading all saved URLs");
  return new Promise((resolve, reject) => {
    console.log("Promise");
    chrome.storage.local.get({pearsurls: []}, function (result) {
      console.log(result.pearsurls);
      resolve(result.pearsurls);
    });
  });
}

      

Note: your original function ends before completing chrome.storage.local.get

doing its job. The array is pearsurls

returned empty at first, and it is filled at any time after the code is executed using the callback function (result) ...

.

+2


source







All Articles