How to find event listeners on a DOM node when debugging or from the JavaScript code?

前端 未结 19 2498
臣服心动
臣服心动 2020-11-21 05:34

I have a page where some event listeners are attached to input boxes and select boxes. Is there a way to find out which event listeners are observing a particular DOM node a

19条回答
  •  名媛妹妹
    2020-11-21 06:27

    Fully working solution based on answer by Jan Turon - behaves like getEventListeners() from console:

    (There is a little bug with duplicates. It doesn't break much anyway.)

    (function() {
      Element.prototype._addEventListener = Element.prototype.addEventListener;
      Element.prototype.addEventListener = function(a,b,c) {
        if(c==undefined)
          c=false;
        this._addEventListener(a,b,c);
        if(!this.eventListenerList)
          this.eventListenerList = {};
        if(!this.eventListenerList[a])
          this.eventListenerList[a] = [];
        //this.removeEventListener(a,b,c); // TODO - handle duplicates..
        this.eventListenerList[a].push({listener:b,useCapture:c});
      };
    
      Element.prototype.getEventListeners = function(a){
        if(!this.eventListenerList)
          this.eventListenerList = {};
        if(a==undefined)
          return this.eventListenerList;
        return this.eventListenerList[a];
      };
      Element.prototype.clearEventListeners = function(a){
        if(!this.eventListenerList)
          this.eventListenerList = {};
        if(a==undefined){
          for(var x in (this.getEventListeners())) this.clearEventListeners(x);
            return;
        }
        var el = this.getEventListeners(a);
        if(el==undefined)
          return;
        for(var i = el.length - 1; i >= 0; --i) {
          var ev = el[i];
          this.removeEventListener(a, ev.listener, ev.useCapture);
        }
      };
    
      Element.prototype._removeEventListener = Element.prototype.removeEventListener;
      Element.prototype.removeEventListener = function(a,b,c) {
        if(c==undefined)
          c=false;
        this._removeEventListener(a,b,c);
          if(!this.eventListenerList)
            this.eventListenerList = {};
          if(!this.eventListenerList[a])
            this.eventListenerList[a] = [];
    
          // Find the event in the list
          for(var i=0;i

    Usage:

    someElement.getEventListeners([name]) - return list of event listeners, if name is set return array of listeners for that event

    someElement.clearEventListeners([name]) - remove all event listeners, if name is set only remove listeners for that event

提交回复
热议问题