3

There is this answer: can I programmatically examine and modify Javascript event handlers on html elements? but it doesn't provide the runtime solution

1 Answer 1

4

There isn't any direct API for this, but it can be accessed in a kind of intrusive way.

By overriding HTMLElement.prototype.addEventListener we can catch added events and store them in an array for example.

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)
}

Full snippet with example:

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Just perfect fix!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.