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 wha
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"]
}
manifest_version
must be there and it must be 2
.activeTab
permission has been added.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.
Instead of specifying a popup page, use the chrome.browserAction.onClicked
API, documented here.
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')});
This was just what I needed but I should add this: If all you need is a one-time event like when a user clicks on the extension's icon, then Background Pages is a waste of resources as it will run in the background ALL the time. Use Event Pages instead:
"background": {
"scripts": ["script.js"],
"persistent": false
}
you need to add a background file. but firstly ou need to add an attribute in manifest.json like,
"background":{
"scripts":["background.js"]
}
now name a file in your extension folder as background.js there is a way of sending objects from background to your content scripts suppose your content script is named content.js then what you need to do is write this code snippet in background.js file
chrome.browserAction.onClicked.addListener(sendfunc);
function sendfunc(tab){
msg={txtt:"execute"};
chrome.tabs.sendMessage(tab.id,msg);
}
what the above code is doing is sending an object named msg to content page and this msg object has a property txtt which is equal to "execute". what you need to do next is compare the values in content script as
chrome.runtime.onMessage.addListener(recievefunc);
function receivefunc(mssg,sender,sendResponse){
if(mssg.txtt==="execute"){
/*
your code of content script goes here
*/
}
}
now whenever you click the extension icon an object named msg is sent from background to content. the function "recievefunc()" will compare its txtt property with string "execute" if it matches your rest of the code will run.
note: msg,txtt,sendfunc,receivefunc,mssg all are variables and not chrome keywords so you can use anything you want.
hope it helps.
:)