3

I'm new to WebExtensions and JavaScript. I'm trying to write a little extension with a pageAction button that simply saves the current URL to local storage when clicked (i.e. some very simple 'favourite' function). I am, however, having trouble with using chrome.storage.local.set() and .get(). I've been looking at code in this question and this question to try and reuse it for my purposes, but failed miserably. Here is what I have at the moment.

The saveURL() function is supposed to load the array in local storage, update it with a new URL, and save it back to local storage (for now, I just have a dud string that I'm trying to push to that 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 loadURLs() function is supposed to retrieve stuff from local storage. I'm using a default in storage.local.get() to initialise the array the first time it is used.

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 [  ]

I.e. my loadURLs() function doesn't seem to be doing anything... What am I doing wrong?

Makyen
  • 31,849
  • 12
  • 86
  • 121
linguist
  • 133
  • 1
  • 9
  • While [edit]s to the question to provide additional information are encouraged, edits which change the question sufficiently to invalidate an already posted answer are not permitted. The consensus is that any user with [edit privileges](http://stackoverflow.com/help/privileges/edit) should revert such edits. I will do so shortly after posting this comment. Please note that this does not prevent you from completely changing a question prior to any answers being posted. You should post a [new question](http://stackoverflow.com/questions/ask) on your new issue. – Makyen Jul 27 '17 at 08:15
  • You can find the source for your most recent changes [here](https://stackoverflow.com/revisions/1162736c-800a-4305-ab4f-85c38a07153d/view-source). I hope that it assists in posting a [new question](http://stackoverflow.com/questions/ask) on your new issue. It can also be beneficial to link to this question to provide context for your new question, but the new question should also be self contained. Please understand that a single question is *not* intended as an interactive debugging session. If you have new issues after getting answers, you should post a new question. – Makyen Jul 27 '17 at 08:21
  • Note also that there's nothing wrong with a question being closed as a duplicate. Duplicates serve as signposts allowing other people who are searching for answers to find the answers on the duplicate-target. – Makyen Jul 27 '17 at 08:22
  • Next time, please include a *complete* [mcve] that duplicates the problem. For Chrome extensions or Firefox WebExtensions this almost always means including your *manifest.json* and some of the background, content, and/or popup scripts/HTML. Questions seeking debugging help ("why isn't this code working the way I want?") must include: (1) the desired behavior, (2) a specific problem or error and (3) the shortest code necessary to reproduce it *in the question itself*. Please also see: [What topics can I ask about here?](http://stackoverflow.com/help/on-topic), and [ask]. – Makyen Jul 27 '17 at 08:24
  • For Firefox WebExtensions it's helpful if you *don't* break functions into separate code blocks. Please have all the code that you are showing which is contained in a single file in a single code block which explicitly specifies the file (e.g. normal text saying my *background.js*: [then a code block]. Problems/issues can significantly depend on exactly which file what code is in. Having code in a single code block *per file* makes it much easier to determine what's going on. – Makyen Jul 27 '17 at 08:27
  • Ok! Apologies! I'll post to a new question. – linguist Jul 27 '17 at 10:09
  • No problem. You clearly didn't know. Unfortunately, there are things about Stack Overflow that are not clearly stated in most of the docs I've read from the [help center](https://stackoverflow.com/help). I was not intending to chastise. I was only intending to inform and facilitate you having the information (both policy and what you had written) for your next question. I look forward to seeing it. – Makyen Jul 27 '17 at 10:15
  • Many thanks for all the advice! It will definitely help for the next question! – linguist Jul 27 '17 at 21:03

1 Answers1

2

You function loadURLs is not either async or returns a Promise, so it ends 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 chrome.storage.local.get is finished doing its job. The array pearsurls is first returned empty, and it gets populated anytime after the execution of the code, using the callback function (result) ....

lilezek
  • 6,976
  • 1
  • 27
  • 45
  • Thanks for the explanation, but no, it doesn't seem to solve the problem. Now my saveURL() function doesn't print anything anymore to the console. – linguist Jul 23 '17 at 11:05
  • Does it freeze in the first or the second call to loadURLs? – lilezek Jul 23 '17 at 11:07
  • Already the first time. Now my only output to the console are the 'Save URL...' and "Loading saved URLs" comments. – linguist Jul 23 '17 at 11:09
  • Did `console.log(result.pearsurls);` got called anytime? – lilezek Jul 23 '17 at 11:15
  • Actually, no. Nothing. – linguist Jul 23 '17 at 11:19
  • Well, that's quite weird. I've added a `console.log`, can you debug if the promise is being executed? – lilezek Jul 23 '17 at 15:57
  • Sorry for delayed answer. Yes, the promise is executed... Is there anything I should check outside of this call, which could be messing things up? I guess I could have made a mistake somewhere else... – linguist Jul 25 '17 at 11:25
  • 1
    All I see is that this snippet now with Promises should work according to chrome documentation. You could check if lastError is changed. https://developer.chrome.com/extensions/runtime#property-lastError – lilezek Jul 26 '17 at 17:22