I have a simple chrome extension that automatically closes new tabs. The goal is for the extension to toggle on/off via clicking the browser icon. I'm able to activate it, however I'm unable to turn it off. Here's what I have so far:
var enable=false;
chrome.browserAction.onClicked.addListener(function (tab) {
enable = enable ? false : true;
if(enable){
chrome.tabs.onCreated.addListener(function (tab) {
chrome.tabs.remove(tab.id);
});
chrome.browserAction.setIcon({path: 'on.png'});
}
else{
chrome.browserAction.setIcon({path: 'icon.png'});
// I'm not sure what to put here
}
});
I have 2 different images to represent the on/off state which is working fine, however the listener remains active. I've tried removeListener to no avail. Any help would be much appreciated!
You have to use a named function in order to use removeListener
:
function myListener(tab){
chrome.tabs.remove(tab.id);
}
var enable=false;
chrome.browserAction.onClicked.addListener(function (tab) {
enable = !enable;
if(enable){
chrome.tabs.onCreated.addListener(myListener);
chrome.browserAction.setIcon({path: 'on.png'});
}
else{
chrome.browserAction.setIcon({path: 'icon.png'});
chrome.tabs.onCreated.removeListener(myListener);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.