Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run script each time Chrome extension icon clicked

How do I write a chrome extension such that every time a user clicks the icon, my script is run but no popup is opened? (I would look this up in the docs myself but for whatever reason they suddenly stopped working, 404ing every page, as I got to this point).

I'm assuming it's just setting up the manifest correctly. Here's what I have now:

{   "name": "My Extension",   "version": "0.1",   "description": "Does some simple stuff",   "browser_action": {     "popup" : "mine.html",     "default_icon": "logo.png"   },   "permissions": [     "notifications"   ] } 
like image 603
Endophage Avatar asked Aug 23 '11 22:08

Endophage


People also ask

Do Chrome extensions work automatically?

How to get chrome extensions automatically installed and sync on all your devices. When you turn on Google Chrome browser sync, then all your chrome extensions will be automatically installed on all your devices. Also, the settings and state for all these extensions will be the same on all your devices.

Are Chrome extensions spyware?

Security researchers discovered 111 malicious extensions that were downloaded by users of the Google Chrome browser and spread dangerous spyware.


2 Answers

Remove popup from your browser_action section of the manifest and use background pages along with browser Action in the background script.

chrome.browserAction.onClicked.addListener(function(tab) { alert('icon clicked')}); 
like image 127
arunkumar Avatar answered Sep 16 '22 15:09

arunkumar


First, if you don't want to show a popup, remove "popup" : "mine.html" from your manifest.json (shown in your question).

Your manifest.json will look something like this:

{   "name": "My Extension",   "version": "0.1",   "manifest_version" : 2,   "description": "Does some simple stuff",   "background" : {     "scripts" : ["background.js"]   },   "browser_action": {     "default_icon": "logo .png"   },   "permissions": ["activeTab"] } 
  • Note that manifest_version must be there and it must be 2.
  • Note that the activeTab permission has been added.
  • Note that you can only do one thing when the browser action button is clicked: either you can show a popup, or you can execute a script, but you can't do both.

Second, to execute a script when the icon is clicked, place the code below in your background.js file (the filename is specified in your manifest.json):

chrome.browserAction.onClicked.addListener(function(tab) {    chrome.tabs.executeScript(null, {file: "testScript.js"}); }); 

Finally, testScript.js is where you should put the code you want to execute when the icon is clicked.

like image 30
yogesh kumar Avatar answered Sep 18 '22 15:09

yogesh kumar