问题
I have created my first chrome extension which adds event handlers to all the anchor elements on the page on clicking. If the user clicks the icon second time the event handlers are reattached to the anchor elements and are executed twice. What I need following
- Click the browser action.
- Add the events to the anchor elements
- If possible give a visual cue in the browser action icon that the extension is active currently.
- Clicking again on the extension should remove the event handlers and again shows the extension icon as disabled.
Is this possible?
Following is what I have tried till now.
manifest.json
{
"name":"NameExtension",
"version":"1.0",
"description":"Here goes the description",
"manifest_version":2,
"browser_action":{
"default_icon":"16x16.png"
},
"background":{
"scripts":["background.js"]
},
"permissions":[
"tabs","http://*/*","https://*/*"
]
}
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file: "contentscript.js"});
});
contentscript.js
var all = document.getElementsByTagName('a');
for(var i=0; i<all.length;i++){
all[i].addEventListener('click',myHandler, false);
}
myHandler = function(event){
alert(event.target.innerText);
}
I would want the above handler to be toggled on anchors as the extension_browser_action is clicked and re-clicked. Also if the extension_browser-action_icon can give some visual feedback regarding the state.
回答1:
I was able to do this with following in my background.js where contentscript adds the handlers and togglecontentscript removes them.
var x = false;
disableBrowserAction();
function disableBrowserAction(){
chrome.browserAction.setIcon({path:"inactive.png"});
chrome.tabs.executeScript(null, {file: "togglecontentscript.js"})
}
function enableBrowserAction(){
chrome.browserAction.setIcon({path:"active.png"});
chrome.tabs.executeScript(null, {file: "contentscript.js"});
}
function updateState(){
if(x==false){
x=true;
enableBrowserAction();
}else{
x=false;
disableBrowserAction();
}
}
chrome.browserAction.onClicked.addListener(updateState);
来源:https://stackoverflow.com/questions/18528009/how-to-toggle-actions-of-a-browser-action