Search code examples
javascriptgoogle-chrome-extensiondom-events

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 screenshot (arrow added for emphasis):

Removing an event listener with Chrome dev tools

I'd like to write a Chrome extension that automatically removes event listeners from any web page (I'm trying to write a Chrome extension to disable smooth scrolling on any website that tries to force it upon you -- I figure removing the 'wheel' listener from <body> is the most direct route to do this). Is there any JavaScript API available for accessing and modifying this list of event listeners from a Chrome extension, or is it limited to the dev tools GUI?

To be clear, I'm aware of removeEventListener(), but that method requires that you have a reference to the original listener object -- I have no such reference, so that method won't suit my purposes.


Solution

  • 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.