Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate getEventListeners() return object

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.

like image 296
pure_bliss Avatar asked Oct 27 '17 12:10

pure_bliss


2 Answers

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.

like image 130
glutengo Avatar answered Nov 06 '22 03:11

glutengo


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, not sure what is your use case, but you might want to use different method for getting event listeners.

like image 43
Martin Adámek Avatar answered Nov 06 '22 02:11

Martin Adámek