0

I'm trying to capture all DOM events on a page. This is the source code I've come up with to do so. It requires jQuery. Is there a better implementation out there? See any problems with my implementation?

// required jQuery

$('*').each(function () {
    var ignore = [
        'mousemove', 'mouseover',  'mouseout',  'mouseenter', 'mouseleave'
    ];

    for (var key in this) {
        if (key.substring(0, 2) === 'on') {
            $(this).on(key.substr(2), function (event) {
                var eventName = event.type,
                    tag = this.tagName.toLowerCase(),
                    id = this.id ? ('#' + this.id) : '';

                if (ignore.indexOf(eventName) === -1) {
                    console.log(tag + id + ' ' + eventName);
                }
            });
        }
    }
});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
core
  • 32,451
  • 45
  • 138
  • 193
  • 1
    Note that if any plugins add events before you do, it's possible for the events to be canceled before you get to them. If you're using chrome, there's a debug method you can call in the console that will log all events that happen of a specific type on a specific element. – Kevin B Oct 09 '14 at 15:26
  • 5
    Questions about improving working code should be asked on our [codereview.se] sister site. – Frédéric Hamidi Oct 09 '14 at 15:27
  • What is that "debug method", Kevin B? – core Oct 09 '14 at 15:30
  • `monitorEvents(element, event)` for example, `monitorEvents(document.body)` however, there's an even better option: http://stackoverflow.com/questions/10213703/how-do-i-view-events-fired-on-an-element-in-chrome-web-developer – Kevin B Oct 09 '14 at 15:33

2 Answers2

0

Maybe something like this:

function doSomething() { console.log('yay'); }

var eventName,
    prefix;

for (var key in document) {
    prefix = key.substr(0, 2);

    if (prefix === "on") {
        eventName = key.substr(2);        
        document.addEventListener(eventName, doSomething, true);
    }
}

It doesn't require jQuery and adds the listeners in capture mode, which means that if propagation is stopped the event will be triggered anyway. Of course you can add filtering if you like.

Fiddle

STT
  • 668
  • 4
  • 12
-1

Perhaps using the built-in _data helper, something like this?

$('*').each(function (i, el) {
  var events = $._data(el, 'events');
  if (events) {
    console.log(el);
    for (var p in events) {
      if (ignore.indexOf(p) === -1) { console.log(p); }
    }
  }
});

(Try adding this to the console of this page - you'll see the elements and their events scroll past).

Andy
  • 61,948
  • 13
  • 68
  • 95