The following one-liner is the plain JS equivalent of monitorEvents(document)
in Chrome DevTools, which also works in Firefox:
// https://stackoverflow.com/a/72945018/319266
for (const key in document) if (key.startsWith('on')) document.addEventListener(key.slice(2), console.log);
Or as function, simplified from Paul Kinlan's original 2016 blogpost:
// https://stackoverflow.com/a/72945018/319266
function monitorEvents(element) {
for (const key in element) {
if (key.startsWith('on')) {
element.addEventListener(key.slice(2), console.log);
}
}
}
I recommend bookmarking the one-line snippet rather than the function, since the one-liner actually does what one typically wants (monitor the document) rather than only defining a function.
The benefit of a function is to be able to monitor only part of the page (to reduce noise from unrelated areas), and to be able to unmonitor it without having to reload the page. Below is a modified version that includes the missing unmonitorEvents()
function to do exactly that.
// Usage:
// monitorEvents(document)
// monitorEvents(document.querySelector('#app'))
// unmonitorEvents(...)
//
// https://stackoverflow.com/a/72945018/319266
function monitorEvents(element) {
for (const key in element) {
if (key.startsWith('on')) {
element.addEventListener(key.slice(2), monitorEvents.log);
}
}
}
monitorEvents.log = (e) => console.log(e);
function unmonitorEvents(element) {
for (const key in element) {
if (key.startsWith('on')) {
element.removeEventListener(key.slice(2), monitorEvents.log);
}
}
}