0

I am trying to pull the boolean value of a checkbox in my popup.html file in my chrome extension. I have this:

var highlightedCheckBoxVal = $("#highlightedCheckbox").prop("checked");

function getAsync(valueToGet) {
    return new Promise((resolve) => {
        chrome.storage.sync.get(valueToGet, (value) => {
            resolve(value);
            console.log("resolved");
        })
    })
}


//returns object - I want it to return true or false
$(document).keyup(async function (e) {
    if (e.keyCode == 120) {
        getAsync("highlightedCheckBoxVal").then(val => {
            console.log(val);
        });
    }
});

The console returns an object, and I want it to return a boolean value. I think this is because getAsync is returning a promise, but how can I make that promise a boolean value?

I have also tried logging val.valueOf().

wOxxOm
  • 65,848
  • 11
  • 132
  • 136

1 Answers1

1

As we can see in the documentation the callback receives an object that contains all requested keys (you can request an array of strings) so the solution is to extract the key as result[key].

function getAsync(key) {
  return new Promise((resolve) => {
    chrome.storage.sync.get(key, (data) => resolve(data[key]));
  });
}
wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • Although this makes sense, the console is now returning undefined. – Graham Billington Mar 12 '20 at 13:46
  • 1
    @GrahamBillington it means you're not saving the value correctly, for example the common pitfall is not setting the key correctly as `{[keyVariable]: value}` – wOxxOm Mar 12 '20 at 13:47
  • Where do I set the key as you explained? @wOxxOm – Graham Billington Mar 12 '20 at 13:48
  • 1
    Uhm? In the code that sets the value. To read the value you need to write it first. – wOxxOm Mar 12 '20 at 13:49
  • The value is set as `$("#highlightedCheckbox").prop("checked");`. How would I set it 'correctly' – Graham Billington Mar 12 '20 at 13:51
  • This code doesn't set anything in storage. See the documentation: you need to use chrome.storage.sync.set. BTW this topic looks like the [yesterday's question](https://stackoverflow.com/questions/60641541/how-and-where-do-i-store-user-preferences-with-the-chrome-storage-api-in-a-chrom). – wOxxOm Mar 12 '20 at 13:52
  • It is similar, yes. Same problem, different approach. – Graham Billington Mar 12 '20 at 14:06
  • My plan is to set the value in the storage with the boolean value of the function. The problem still persists as the promise is returning undefined. Is there something I am not understanding? @wOxxOm – Graham Billington Mar 12 '20 at 14:16
  • Like I said, you need to set the value in storage to be able to read it afterwards. Use chrome.storage.sync.set in a listener for `change` event of the checkbox element. – wOxxOm Mar 12 '20 at 14:17