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?