【问题标题】:How to list event listeners of the html element in runtime without the dev tools?如何在没有开发工具的情况下在运行时列出 html 元素的事件侦听器?
【发布时间】:2022-07-13 00:18:35
【问题描述】:

有这个答案:can I programmatically examine and modify Javascript event handlers on html elements? 但它不提供运行时解决方案

【问题讨论】:

    标签: javascript javascript-events


    【解决方案1】:

    没有任何直接的API,但可以通过一种侵入性的方式访问它。

    例如,通过覆盖HTMLElement.prototype.addEventListener,我们可以捕获添加的事件并将它们存储在一个数组中。

    const listeners = []
    const originalAddEventListener = HTMLElement.prototype.addEventListener
    HTMLElement.prototype.addEventListener = function(type, listener, options) {
        listeners.push({
        element: this,
        type,
        listener,
        options
      })
      // call the original listener with current this and provided arguments
      return originalAddEventListener.call(this, type, listener, options)
    }
    

    完整的 sn-p 示例:

    const listeners = []
    const originalAddEventListener = HTMLElement.prototype.addEventListener
    HTMLElement.prototype.addEventListener = function(type, listener, options) {
      listeners.push({
        element: this,
        type,
        listener,
        options
      })
      return originalAddEventListener.call(this, type, listener, options)
    }
    
    document.querySelector('p').addEventListener('click', () => {
      console.log('clicked')
    }, false)
    
    document.querySelector('button').addEventListener('click', () => console.log(listeners))
    p {
      width: 100px;
      height: 100px;
      background: red;
      color: white;
    }
    <button>list listeners</button>
    <p>click me</p>

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 2014-12-25
      • 1970-01-01
      • 1970-01-01
      • 2022-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多