Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
List all event listeners in a document
const listeners = (function listAllEventListeners() {
let elements = [];
const allElements = document.querySelectorAll('*');
const types = [];
for (let ev in window) {
if (/^on/.test(ev)) types[types.length] = ev;
}
for (let i = 0; i < allElements.length; i++) {
const currentElement = allElements[i];
for (let j = 0; j < types.length; j++) {
if (typeof currentElement[types[j]] === 'function') {
elements.push({
"node": currentElement,
"listeners": [ {
"type": types[j],
"func": currentElement[types[j]].toString(),
}]
});
}
}
}
return elements.filter(element => element.listeners.length)
})();
console.table(listeners);
@tkafka

This comment has been minimized.

Copy link

@tkafka tkafka commented Mar 6, 2019

Here's a fork that lists events on document as well: https://gist.github.com/tkafka/1c5174ed5b446de7dfa4c04a3b09c95f

@alex2844

This comment has been minimized.

@joeyhub

This comment has been minimized.

Copy link

@joeyhub joeyhub commented Jan 14, 2020

I use this to remove and create a tree of event listeners for debugging:

(document=>{
    const all={};
    for(let tag of document.querySelectorAll('*')) {
        const events=getEventListeners(tag);
        if(Object.keys(events).length) {
            for(let [event,listeners] of Object.entries(events))
                for(let listener of listeners)tag.removeEventListener(listener.type,listener.listener,listener.useCapture);
            const path=(node=>{
                const parts=[];
                while(node.parentNode!==null) {
                    parts.push(`${node.nodeName}[${[...node.parentNode.children].indexOf(node)}]`);
                    node=node.parentNode
                }
                return parts.reverse()
            })(tag),name=path.pop();
            let node=all;
            for(let part of path) {
                if(!(part in node))node[part]={};
                node=node[part];
            }
            node[name]=[tag, events]
        }
    }
    return all
})(document)

It was originally a one liner hence the weird formatting. I'm not sure getEventListeners is standard JS but it's in the Chrome console.

@james-jhang

This comment has been minimized.

Copy link

@james-jhang james-jhang commented Feb 11, 2020

@joeyhub No, it is not a standard api in js. You can only use getEventListeners in dev tool of Chrome (https://developers.google.com/web/tools/chrome-devtools/console/utilities).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.