jquery - Chrome Extension: Unbind event listener added by script executed on the fly -
i have chrome extension bind mousedown event listener on "body" when browser action clicked. , when browser action clicked again, unbind mousedown event.
but reason, unbind not working though logs codes executed. have tried bind()/unbind() methods no avail.
any 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 bind event)
console.log("on"); $("body").on('mousedown.custom', function(e){ e.preventdefault(); // something... });
off.js (script unbind event)
console.log('off'); $("body").off('mousedown.custom');
executing whole jquery library on mouse click seems redundant me. may explain problem (because both on , off). try load & execute jquery outside of click event handler or @ least make sure doesn't run twice.
also way you're communicating content script not ideal. don't need different files 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(); });
Comments
Post a Comment