Search code examples
javascriptjquerydebuggingjquery-mobilejquery-events

Javascript Debugging - How to break on all unknown click events


I have a jQuery mobile project and in order to close (most) popups I noticed I have to click twice in an area other than the popup. In these cases it seems the first click removes the #&ui-state=dialog from the URL address bar while the second actually removes the popup.

I've checked for multiple includes of the same JS file and there is only one occurrence when viewing the source. I'm refreshing the page directly so there is no chance of a second include of the JS file from navigation either. As far as I can tell (and I'm pretty sure) there are not multiple custom click events bound to the button which triggers the pop-up (Maybe jQuery Mobile behind the scenes stuff, but not custom).

Is there a way for me to essentially listen for all click events as part of debugging and see what is going on with them? I've added breaks to the custom JS code which opens the popup, and it only executes once. But there is more going on and I don't know where it is coming from or how I can find it.


Solution

  • You could hijack the addEventListener method which would give you the option of knowing when an event is registered and even react to that event.

    var oldAddEventListener = EventTarget.prototype.addEventListener;
    EventTarget.prototype.addEventListener = function(cb) {
      var customCB = function() {
        console.log('Hijacked event handler');
        return cb.apply(this, arguments);
      };
    
      console.log('Hijacked add event listener');
      return oldAddEventListener.apply(this, arguments);
    };
    

    If you want to capture every event, make sure you load in this code before any other additional code.

    This works because Element inherits addEventListener from EventTarget. By overwriting that method on the prototype, this ensures that every Element will use your custom method when attaching an event listener.