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

前端 未结 19 2546
臣服心动
臣服心动 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:11

    It is possible to list all event listeners in JavaScript: It's not that hard; you just have to hack the prototype's method of the HTML elements (before adding the listeners).

    function reportIn(e){
        var a = this.lastListenerInfo[this.lastListenerInfo.length-1];
        console.log(a)
    }
    
    
    HTMLAnchorElement.prototype.realAddEventListener = HTMLAnchorElement.prototype.addEventListener;
    
    HTMLAnchorElement.prototype.addEventListener = function(a,b,c){
        this.realAddEventListener(a,reportIn,c); 
        this.realAddEventListener(a,b,c); 
        if(!this.lastListenerInfo){  this.lastListenerInfo = new Array()};
        this.lastListenerInfo.push({a : a, b : b , c : c});
    };
    

    Now every anchor element (a) will have a lastListenerInfo property wich contains all of its listeners. And it even works for removing listeners with anonymous functions.

提交回复
热议问题