Work on my most recent Firefox Webextension requires that I call into an async API function (browser.storage.local.get()).
This, however, means the result of the API call isn't easily available from a getter. Not without using the "await" keyword inside an async function anyways.
Is there any way to abstract this away, so the getter can be used regularly, from any function?
Here's the (fairly early) codebase.
class CookieButton {
async getStorageAsync() {
var storage = await browser.storage.local.get();
return storage
}
get ButtonState() {
console.log("GET")
return this.getStorageAsync().then(x => x.buttonState)
}
set ButtonState(value) {
console.log("SET")
return browser.storage.local.set({ buttonState: value })
}
constructor(ButtonState) {
this.setup()
}
async enable() {
browser.privacy.websites.cookieConfig.set({ value: { behavior: "allow_all" } })
this.ButtonState = 'turn-off';
browser.browserAction.setIcon({ path: 'icons/enabled.png', });
}
async disable() {
browser.privacy.websites.cookieConfig.set({ value: { behavior: "reject_all" } })
this.ButtonState = 'turn-on';
browser.browserAction.setIcon({ path: 'icons/disabled.png', });
}
async setup() {
if (await this.ButtonState == undefined) {
this.ButtonState = "turn-off";
}
if (await this.ButtonState == "turn-on") {
browser.browserAction.setIcon({ path: 'icons/disabled.png', });
}
browser.browserAction.onClicked.addListener(async function (tab) {
var state = await cookieButton.ButtonState;
switch (state) {
case 'turn-on':
cookieButton.enable();
break;
case 'turn-off':
cookieButton.disable();
break;
case 'undefined':
cookieButton.enable();
break;
}
});
}
}
var cookieButton = new CookieButton();
The part in question is the block inside "get ButtonState()".
Say I wanted to log the current state of the Button, as it's saved inside the storage object.
As it stands, I have to use "console.log(await this.ButtonState)", which will only work inside an async function. Ideally, I'd be able to type "console.log(this.ButtonState)" and access the result from anywhere.