how to make on/off buttons/icons for a chrome extension?

后端 未结 1 888
轮回少年
轮回少年 2020-12-10 16:24

I want to let the user decide when they want to run a script, so that when the browser opens, the \"off\" icon is showing and no script runs; but when the user clicks it, it

1条回答
  •  时光取名叫无心
    2020-12-10 16:58

    Alright, so let me make a few changes to your manifest and background pages.

    manifest.json

    "browser_action": {
      "default_icon": "off.png",
      "default_title": "icon"
    },
    

    That will make the default off.png. As for the icons section, read the docs to see what it is used for, but for now just remove it entirely. Also remove what you have in your contentScripts section. If you want to inject it programmatically then there is no need to list it in the manifest.

    Next some changes to your background page to make it a bit more clean:

    background.js

    var toggle = false;
    chrome.browserAction.onClicked.addListener(function(tab) {
      toggle = !toggle;
      if(toggle){
        chrome.browserAction.setIcon({path: "on.png", tabId:tab.id});
        chrome.tabs.executeScript(tab.id, {file:"SCRIPT.user.js"});
      }
      else{
        chrome.browserAction.setIcon({path: "off.png", tabId:tab.id});
        chrome.tabs.executeScript(tab.id, {code:"alert()"});
      }
    });
    

    0 讨论(0)
提交回复
热议问题