Retrieve JS Events: how to get all of them

Tue, Dec 3, 2013 programming dom, events, javascript, nodejs, phantomjs Reading time: 2 min.

I was trying face an apparently huge problem, collect all the events bound to the DOM elements. Then I realised that the main obstacle was the browser, yes the browser.
Because of the way the browser manage the events.

So I started my research about it, nothing came from Google or StackOverflow.

This answer made me think and for a second I was about to give up on that:

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.

bobince

There are few ways to bind an event we should focus on:

The last 2 are not possible to be retrieved without some workounds because they are handled internally by the browser and they don’t leave any trace in the DOM.

I’ve developed a plain JS class while I was facing this problem when working on my own project salmonJS, a web spider which is using PhantomJS and Node.js. So I came with this solution which seems to be the most appropriate one to run on PhantomJS (and I believe it works fine with CasperJS as well).

My personal approach was overriding the default behaviour at the beginning of the page load, so nothing else can try to bind an event before initialise the “interceptor”.

There is nothing that needs to be configured to make it working, just include it in your page before EVERYTHING else.

You can collect at any time the events just calling:

1 var events = eventContainer.getEvents();