If you really had to, a general way to do this would be to patch EventTarget.prototype.addEventListener
:
const listeners = [];
const orig = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function(...args) {
if (this instanceof HTMLElement) {
listeners.push({
type: args[0],
fn: args[1],
target: this,
});
}
return orig.apply(this, args);
};
document.body.addEventListener('click', () => console.log('body clicked'));
console.log(listeners[0].fn);
click this body
To find listeners attached to an element, iterate through the listeners
array and look for target
s which match the element you're looking for.
To be complete, also patch removeEventListener
so that items can be removed from the array when removed.
If you need to watch for listeners attached via on
, then you'll have to do something similar to the above to patch the HTMLElement.prototype.onclick
getter/setter, and for each listener you want to be able to detect.
That said, although you said you want a generic solution, rather than patching built-in prototypes, it'd be better to add the listeners through jQuery or through your own function.