Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Records every DOM event and then set ups a listener that shows
// the full CSS selector path of the target that triggered the event.
const getPathForElement = el => {
const names = [];
while (el.parentNode) {
if (el.id) {
names.unshift(`#${el.id}`);
break;
} else {
if (el === el.ownerDocument.documentElement) {
names.unshift(el.tagName);
}
else {
for (
let count = 1, e = el;
e.previousElementSibling;
e = e.previousElementSibling, count++
)
names.unshift(`${el.tagName.toLowerCase()}:nth-child(${count})`);
}
el = el.parentNode;
}
}
return names.join(" > ");
}
const getAllEventNames = () => (
Object
.getOwnPropertyNames(document)
.concat(
Object.getOwnPropertyNames(
Object.getPrototypeOf(Object.getPrototypeOf(document))
)
)
.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(window)))
.filter(
i => !i.indexOf("on") &&
(document[i] == null || typeof document[i] === "function")
)
.filter((elem, pos, self) => self.indexOf(elem) === pos)
);
const getAllEventListenerNames = () => getAllEventNames().map(eventName => eventName.slice(2));
const events = getAllEventListenerNames();
const logEvent = eventName => e => {
if (e.target) console.log(eventName, getPathForElement(e.target));
};
for (const event of events) {
document.body.addEventListener(event, logEvent(event));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment