在浏览器操作单击时切换图标

时间:2017-06-19 13:32:38

标签: javascript firefox firefox-webextensions browser-extension browser-action

如何在浏览器操作上切换我的扩展程序图标?

的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 - off.svg
on.svg - on.svg

现在,只要我将扩展程序加载到浏览器,上面的代码就会自动将图标从“off.svg”切换为“on.svg”。如何在浏览器操作图标点击上设置相同的内容。

1 个答案:

答案 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.