如何使打开/关闭按钮/图标的chrome扩展

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

本文关键字:chrome 扩展 图标 关闭按钮 何使打      更新时间:2023-09-26

我想让用户决定何时要运行脚本,这样当浏览器打开时,"关闭"图标显示,没有脚本运行;但是当用户单击它时,它会变为"打开"图标并执行一个用户脚本,直到用户单击"关闭"。我有两个png图标,每个是32x32: on.pngoff.png

我的两个问题:

  1. 如何将默认图标设置为off.png?我在我的manifest.json中尝试了这个,但它没有设置图标,而是显示了一个拼图块(我假设是默认的):

    ...
    "browser_action": {
       "default_icon": {
           "32": "off.png"
           },
       "default_title": "icon"
    },
    "icons": {
       "32": "on.png",
       "32": "off.png"
    },
    "background": {
       "scripts": ["background.js"] 
    }, 
    "content_scripts": [{ 
       "js": ["SCRIPT.user.js"]
    ...
    
  2. 这是我的background.js,在那里我暂时做了一个快速的功能来尝试和切换基于onClicked的开/关

    var status = 0;
    function toggle() {
    if (status == 0){
        chrome.browserAction.setIcon({path: "on.png", tabId:tab.id}); // so it's set for the tab user is in
        chrome.tabs.executeScript(tab.id, file:"SCRIPT.user.js"); //execute for this tab
        status++;
    }
    if (status == 1){
        chrome.browserAction.setIcon({path: "off.png", tabId:tab.id});
        chrome.tabs.executeScript(tab.id, code:"alert()"); // execute nothing when off
        status++;
    }
    if (status > 1)
        status = 0; // toggle
    }
    chrome.browserAction.onClicked.addListener(function(tab) {
        toggle();
    });
    

(我应该提到,当我加载文件夹容纳我的脚本,图标和manifest在"加载解压扩展",然后选择"检查视图"检查是否有任何立即错误,我看到Uncaught SyntaxError: Unexpected token :在后台。js,虽然我不知道它指的是什么)…在scripts文件夹

中没有显示我的userscript

有什么想法吗?

好的,让我对你的manifest和background页面做一些修改。

manifest.json

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

这将使默认的off.png。至于图标部分,请阅读文档以了解它的用途,但现在只需完全删除它。还要删除contentScripts部分中的内容。如果你想以编程方式注入它,那么就没有必要在清单中列出它。

接下来对您的背景页面进行一些更改,使其更干净:

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()"});
  }
});