Reputation: 1167
I have a Chrome extension that will bind mousedown event listener on "body" when the browser action is clicked. And when the browser action is clicked again, it will unbind the mousedown event.
But for some reason, unbind is not working even though the logs say the codes executed. I have tried bind()/unbind() methods as well to no avail.
Any help is appreciated. Thanks!
manifest.json
{
"name": "My Extension",
"description": "View Font Info",
"manifest_version": 2,
"version": "1",
"permissions": ["tabs", "http://*/*", "https://*/*"],
"browser_action": {
"default_icon": "f.png"
},
"background": {
"scripts": ["background.js"]
}
}
background.js
var toggle = false;
chrome.browserAction.onClicked.addListener(function(tab) {
toggle = !toggle;
if(toggle){
chrome.browserAction.setIcon({path: "f.png", tabId:tab.id});
chrome.tabs.executeScript(tab.id, {file:"jquery.js"}, function(){
chrome.tabs.executeScript(tab.id, {file: "on.js"});
});
}
else{
chrome.browserAction.setIcon({path: "", tabId:tab.id});
chrome.tabs.executeScript(tab.id, {file:"jquery.js"}, function(){
chrome.tabs.executeScript(tab.id, {file: "off.js"});
});
}
});
on.js (script to bind event)
console.log("On");
$("body").on('mousedown.custom', function(e){
e.preventDefault();
// do something...
});
off.js (script to unbind event)
console.log('off');
$("body").off('mousedown.custom');
Upvotes: 1
Views: 704
Reputation: 50109
Executing the whole jQuery library on a mouse click seems redundant to me. It may also explain your problem (because you do it for both ON and OFF). Try to load & execute jQuery outside of the click event handler or at least make sure it doesn't run twice.
Also the way you're communicating with your content script is not ideal. You don't need different files just use message passing
.
background.js
var isjQueryLoaded = {};
function executeAfterjQuery(tabId, fn) {
if (isjQueryLoaded[tabId]) {
fn();
} else {
isjQueryLoaded[tabId] = true;
chrome.tabs.executeScript(tabId, { file:"jquery.js" }, fn);
}
}
var toggle = false;
chrome.browserAction.onClicked.addListener(function (tab) {
toggle = !toggle;
var path = toggle ? "f.png" : "";
var state = toggle ? "on" : "off";
chrome.browserAction.setIcon({ path: path, tabId:tab.id });
executeAfterjQuery(tab.id, function () {
chrome.tabs.sendMessage(tab.id, { state: state });
});
});
script.js
function on() {
// ...
}
function off () {
// ...
}
chrome.extension.onMessage.addListener(
function (message, sender, sendResponse) {
(message.state == "on") ? on() : off();
});
Upvotes: 1