我创建了我的第一个 chrome 扩展程序,它在单击时将事件处理程序添加到页面上的所有 anchor 元素。如果用户第二次单击该图标,事件处理程序将重新附加到 anchor 元素并执行两次。 我需要遵循什么
- 点击浏览器操作。
- 将事件添加到 anchor 元素
- 如果可能,请在浏览器操作图标中提供一个视觉提示,表明该扩展程序当前处于事件状态。
- 再次点击扩展程序应该会删除事件处理程序并再次将扩展程序图标显示为已禁用。
这可能吗?
以下是我到目前为止的尝试。
list .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);
}
我希望在单击并重新单击 extension_browser_action 时在 anchor 上切换上述处理程序。此外,如果 extension_browser-action_icon 可以提供一些关于状态的视觉反馈。
最佳答案
我能够在我的 background.js 中执行此操作,其中 contentscript 添加处理程序并 togglecontentscript 删除它们。
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);
关于google-chrome - 如何切换浏览器操作的操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18528009/