如何在浏览器操作上切换我的扩展程序图标?
的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"
}
});
现在,只要我将扩展程序加载到浏览器,上面的代码就会自动将图标从“off.svg”切换为“on.svg”。如何在浏览器操作图标点击上设置相同的内容。
答案 0 :(得分:1)
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.