Skip to content Skip to sidebar Skip to footer

Can I Remove Event Listeners With A Chrome Extension?

In Chrome's dev tools, there's a lovely interface where you can see all the event listeners attached to a given DOM element, and remove any of them as you see fit. Here's a screens

Solution 1:

eholder0's answer unfortunately doesn't help when the event listener is registered on window (like in your question) or document. For that, one way is that most code and libraries usually registers event listeners on the bubbling phase, by passing in false for the third useCapture parameter of addEventListener (or just not passing it in at all). Since the capturing phase happens first, you can prevent event listeners from being invoked by registering a capturing phase listener that stops further propagation.

So for your case, you can do the following in the extension's content script:

document.addEventListener("wheel", event => event.stopPropagation(), true);

... or more explicitly:

document.addEventListener("wheel", event => event.stopPropagation(), { capture: true });

Notice the third parameter is true to register a capturing phase event listener. Also notice that it does not call event.preventDefault(), so the browser's built-in scrolling function is retained.


An addendum based on the comments: In the case where the handler you want to suppress is on a specific element rather than document, you can also register the capturing handler on that element, so that events in the rest of the document are not impacted.

Solution 2:

Unfortunately because of how event listeners are implemented, this isn't trivially possible. There are some libraries you can use which record calls to add event listeners, thereby giving you a reference to remove. Short of using those or rolling your own, the isn't a simple tool to remove them anonymously.

You can however do something which will effectively remove all listeners, which is to clone the element and replace it with the clone. Cloning does not preserve any listeners on the element or its children, though it does otherwise preserve all attributes. Here's an example of how to do that:

var elem = document.getElementById('foo'),
clone = elem.cloneNode(true);
elem.parentNode.replaceChild(clone, elem);    

Post a Comment for "Can I Remove Event Listeners With A Chrome Extension?"