Created
April 5, 2017 15:40
-
-
Save dmnsgn/36b26dfcd7695d02de77f5342b0979c7 to your computer and use it in GitHub Desktop.
List all event listeners in a document
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
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.
@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
Here's a fork that lists events on document as well: https://gist.github.com/tkafka/1c5174ed5b446de7dfa4c04a3b09c95f