Use Chrome extension to unbind click events?
I'm t开发者_JAVA百科rying to make an extension that unbinds a click event added by the website itself.
The website uses jQuery, which would make this insanely simple:
jQuery('a[rel]').unbind('click');
The problem is that my extension (using "content_scripts") can't access the website's jQuery object and therefore doesn't have the event functions to unbind. I can include a jQuery in my extension, but that wouldn't help, because jQuery stores 'data' in the jQuery object (not in the DOM elements). My jQuery will not have those events stored.
Is there another way? It doesn't have to be pretty. Maybe without "content_scripts"?
var unbind_event_listeners = function (node) {
var parent = node.parentNode;
if (parent) {
parent.replaceChild(node.cloneNode(true), node);
} else {
var ex = new Error("Cannot remove event listeners from detached or document nodes");
ex.code = DOMException[ex.name = "HIERARCHY_REQUEST_ERR"];
throw ex;
}
};
Just call unbind_event_listeners(a_node)
to unbind any listeners from a node. This will work on every node in the document except document
itself. As for window
, you're out of luck. unbind_event_listeners(document.documentElement)
should remove most event listeners attached to nodes in the document.
In the case of a[rel]
, you'd want to do this:
var nodes = document.querySelectorAll("a[rel]"), i = nodes.length;
while (i--) {
unbind_event_listeners(nodes.item(i));
}
If it doesn't need to be pretty and you're okay with doing things slightly hack-like, this should forcefully unbind every click listener bound to that element:
var el = document.querySelector('a[rel]');
el.onclick = function() {};
el.addEventListener = function() {};
or for every element:
Array.prototype.slice.call(document.querySelectorAll('a[rel]')).forEach(function(el) {
el.onclick = function() {};
el.addEventListener = function() {};
});
EDIT: You could maybe do something even uglier and have a content script run at "document_start" and do:
Element.prototype.addEventListener = (function() {
var real = Element.prototype.addEventListener;
return function(ev) {
if (ev === 'click' && this.tagName === 'A' && this.hasAttribute('rel')) {
console.log('try again, jquery!');
} else {
return real.apply(this, arguments);
}
};
})();
精彩评论