7

I am searching for a way to iterate the object getEventListeners(obj) returns. This way, I wouldn't need specific code to iterate event listener types, or to check if they exist on the checked element.

My goal is to remove some event listeners from an element. For example remove all mouse related ones, and keep the others.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
pure_bliss
  • 95
  • 1
  • 1
  • 8

3 Answers3

23

getEventListeners(obj) is only a Google Chrome specific Command Line Tool feature. This means that you can only use this feature inside Chrome Dev Tools when manually typing into the console. You cannot use this method in your actual JavaScript source code.

If you want to achieve what you described, AFAIK you have to keep track of your listeners manually. Check this answer for further instructions.

glutengo
  • 388
  • 3
  • 13
  • the link to Chrome Specific Tools is broken, it's https://developer.chrome.com/docs/devtools/console/utilities/#getEventListeners-function and has a list of all tools. – Stephan Luis Feb 24 '22 at 22:17
15

getEventListeners() will return simple JS object, you can iterate objects like this:

var listeners = window.getEventListeners(document.body);
Object.keys(listeners).forEach(event => {
    console.log(event, listeners[event]);
});

But looks like that getEventListeners method is available only in chrome, and only by manual entry in DevTools.

ocodo
  • 29,401
  • 18
  • 105
  • 117
Martin Adámek
  • 16,771
  • 5
  • 45
  • 64
  • 2
    Thanks, but I didn't realize this is chrome specific :( But this is the answer to the question, so thank you – pure_bliss Oct 28 '17 at 10:12
  • 2
    getEventListeners is not a javascript function (it only works on the dev tools command line) – user1432181 May 14 '21 at 17:06
  • 1
    is there any alternative function of getEventListeners ? which I can use my js file – Arif Aug 25 '22 at 19:26
  • @Arif The alternative is to keep track of the event listeners you attach yourself in an array or object. Of course, this will not track event listeners added by 3rd party code. There is no other alternative. – slebetman May 18 '23 at 08:49
2

I realise this is old, but there is a library that allows for the use of .getEventListeners() function outside of Chrome's Dev Tools

https://github.com/colxi/getEventListeners

let myEl = document.getElementById('someElementId');

// add some event listeners to the Element
myEl.addEventListener('click', e=> console.log('click!') );
myEl.addEventListener('click', e=> console.log('click 2!') );
myEl.addEventListener('mouseover', e=> console.log('mouse over!') );

// retrieve the listeners
console.log( myEl.getEventListeners() );

Might be of help to someone.

W_ Jonesey
  • 25
  • 1
  • 8