A partial archive of discourse.wicg.io as of Saturday February 24, 2024.

[Proposal] EventTarget.prototype.getEventListeners()

leaverou
2017-02-16

Purpose: This would provide a way to get all event listeners added to an element via addEventListener.

Signature: element.getEventListeners([type])

Returns: Array of objects. Each object contains properties for type, callback, options for the arguments that registered the corresponding event listener. Events registered via inline event handlers are not included.

Use cases: This would enable removing events based on arbitrary criteria, instead of requiring a reference to the callback, which causes unnecessary couplings. Typically libraries deal with this by providing their own abstractions for adding events that track the listeners manually. However, this is fragile, as it means listeners not registered via the library cannot be retrieved or removed. Some libraries deal with this by hijacking addEventListener to keep track of listeners, but this is very intrusive for a library and it doesn’t help with any listeners registered before the library was included. Browsers already keep track of event listeners, so it should be relatively easy to expose them, and is on par with the Extensible Web Manifesto principle of exposing browser “magic” via JS APIs.

Edit: WHATWG proposal: https://github.com/whatwg/dom/issues/412

lydell
2017-02-19

Another use case: WebExtensions.

The VimFx extension uses a Firefox API called nsIEventListenerService.getListenerInfoFor. getEventListeners sounds like a great replacement as VimFx transitions to become a WebExtension.

The Vimium (Chrome/Web) extension has a pull request open for hacking addEventListener to be able to keep track of which elements have click handlers.

Both of these extensions try to identify every clickable element on web pages, and let the user click those using the keyboard only.

mkay581
2017-02-27

Nice! I’ve ran into situations where this would be extremely helpful. Would be great if someone picked this up.