How can I toggle my extension icon on browser action onclick?
manifest.json
{
"manifest_version": 2,
"name": "Toggle Icon",
"description": "Toggle browser action Icon",
"version": "1.0",
"homepage_url": "https://www.stackoverflow.com/",
"icons": {
"48": "icons/message-48.png"
},
"background": {
"scripts": ["background.js"]
},
"permissions": [
"tabs"
],
"browser_action": {
"default_icon": "icons/off.svg",
"default_title": "ON"
},
"content_scripts": [
{
"matches": ["http://localhost/*"],
"js": ["content-script.js"]
}
]
}
background.js
browser.browserAction.setIcon({
path: {
19: "icons/on.svg",
38: "icons/on.svg"
}
});
Now the above code will automatically toggle the icon from 'off.svg' to 'on.svg' as soon as I load my extension to the browser. How can I setup the same thing on browser-action icon click.
Probably something like this:
let isEnabled = true
browser.browserAction.onClicked.addListener((tab) => {
isEnabled = !isEnabled
if (isEnabled) {
browser.browserAction.setIcon({
path: {
19: "icons/on.svg",
38: "icons/on.svg"
}
});
} else {
browser.browserAction.setIcon({
path: {
19: "icons/off.svg",
38: "icons/off.svg"
}
});
}
})
(untested)
Please note that by using the browser action as a toggle, you can't have a browser action popup anymore. In case you need such a popup, consider placing a toggle button into the popup.