How to make on / off buttons for chrome extension?

I want the user to decide when he wants to run the script so that when the browser opens, the "off" icon is displayed and the script does not start; but when the user clicks on it, it changes to the "on" icon and executes the user pointer until the user closes. I have two png icons, each of which is 32x32: on.png and off.png .

My two questions are:

  • How to set default icon to my off.png? I tried this in my manifest.json , but did not set the icon, instead showed a piece of the puzzle (I assume the default):

     ... "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"] ... 
  • Here is my background.js where I temporarily made a quick function to try to enable / disable based on onClicked

     var status = 0; function toggle() { if (status == 0){ chrome.browserAction.setIcon({path: "on.png", tabId:tab.id}); // so it 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(); }); 

(I have to mention that when I load the folder where my scripts, icons and manifest are stored in “download unpacked extension” and then select “check looks” to check if something happened right away, I see Uncaught SyntaxError: Unexpected token : in the background .js, although I don’t know what this refers to) ... and it does not seem to show my usercript in the script folder

So any ideas help?

+7
source share
1 answer

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

manifest.json

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

This will do off.png by default. Regarding the icon section, read the docs to find out what it's used for, but for now, just delete it completely. Also delete what you have in the contentScripts section. If you want to enter it programmatically, then there is no need to list it in the manifest.

Further, some changes to your background page will make it cleaner:

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

All Articles