Inspect attached event handlers for any DOM element
Is there any way to view what functions / code are attached to any event for a DOM element? Using Firebug or any other tool.
The Elements Panel in Google Chrome Developer tools has had this since Chrome releases in mid 2011 and Chrome developer channel releases since 2010.
Also, the event listeners shown for the selected node are in the order in which they are fired through the capturing and bubbling phases.
Hit command + option + i on Mac OSX and Ctrl + Shift + i on Windows to fire this up in Chrome
Event handlers attached using traditional element.onclick= handler
or HTML <element onclick="handler">
can be retrieved trivially from the element.onclick
property from script or in-debugger.
Event handlers attached using DOM Level 2 Events addEventListener
methods and IE's attachEvent
cannot currently be retrieved from script at all. DOM Level 3 once proposed element.eventListenerList
to get all listeners, but it is unclear whether this will make it to the final specification. There is no implementation in any browser today.
A debugging tool as browser extension could get access to these kinds of listeners, but I'm not aware of any that actually do.
Some JS frameworks leave enough of a record of event binding to work out what they've been up to. Visual Event takes this approach to discover listeners registered through a few popular frameworks.
Chrome Dev Tools recently announced some new tools for Monitoring JavaScript Events.
TL;DR
Listen to events of a certain type using
monitorEvents()
.Use
unmonitorEvents()
to stop listening.Get listeners of a DOM element using
getEventListeners()
.Use the Event Listeners Inspector panel to get information on event listeners.
Finding Custom Events
For my need, discovering custom JS events in 3rd party code, the following two versions of the getEventListeners()
were amazingly helpful;
getEventListeners(window)
getEventListeners(document)
If you know what DOM Node the event listener was attached to you'd pass that instead of window
or document
.
Known Event
If you know what event you wish to monitor e.g. click
on the document body you could use the following: monitorEvents(document.body, 'click');
.
You should now start seeing all the click events on the document.body
being logged in the console.