I'm doing a Chrome extension and I need the action button to show a badge text "ON" when it is active, and hide this badge when it is disabled. You toggle this state clicking on the action button. I've seen there are other posts trying to do the same in certain way, and there may be another solution, but I also would like to understand why my solution is not behaving in the way I want, specifically to understand how to handle chrome.action.getBadgeText, which is what I'm using to toggle the state of the button. I think it behaves as a promise and that this asynchronous behaviour is causing that the button toggle every two clicks, instead of with only one click. I mean, what I get is if you click twice the button it toggles, but I need to toggle with only one click. This is the code:
event.js relevant code:
let badgeStatus = "";
chrome.action.onClicked.addListener(() => {
getBadgeStatus();
toggleBadgeStatus();
});
function getBadgeStatus() {
chrome.action.getBadgeText({}, (r) => {
badgeStatus = r;
console.log(badgeStatus);
})
}
function toggleBadgeStatus() {
if (badgeStatus != "ON") {
chrome.action.setBadgeText({text: "ON"}, () => {});
setAlarm();
stateDetect();
console.log("Alarm set")
} else {
chrome.action.setBadgeText({text: ""}, () => {});
}
}
Code updated with the suggestion to use chrome.storage.local:
event.js, running on the background:
var badgeStatus;
chrome.runtime.onInstalled.addListener(() => {
var badgeStatus = false;
chrome.storage.local.set({badgeKey: badgeStatus}, () => {});
})
chrome.action.onClicked.addListener(() => {
badgeStatus = chrome.storage.local.get(['badgeKey'], (result) => {
badgeStatus = result.badgeKey;
})
if (!badgeStatus) {
chrome.action.setBadgeText({text: "ON"}, () => {});
badgeStatus = true;
chrome.storage.local.set({badgeKey: badgeStatus}, () => {});
setAlarm();
stateDetect();
console.log("Alarm set")
} else {
chrome.action.setBadgeText({text: ""}, () => {});
badgeStatus = false;
chrome.storage.local.set({badgeKey: badgeStatus}, () => {});
chrome.alarms.clear("video_alarm");
console.log("Alarm clear")
}
});