0

I have a program which runs just fine in the console, because I paste it into the browser console. It uses the console's function getEventListeners which is very handy to get the handlers for specific events. However, I would like to do this for a regular javascript (without console). For example, in the console the code looks like this:

someEl.addEventListener('mousedown', () => { alert('mousedown') });

const mouseDownHandler = getEventListeners(someEl).mousedown[0].listener;

How can I do the same thing without the console? Any help would be appreciated!

Jeanluca Scaljeri
  • 26,343
  • 56
  • 205
  • 333
  • Why do you need this? – Jonas Wilms Apr 29 '19 at 16:07
  • I have my reasons :) I'm doing tests with WebDriverIO and need to do some interaction with the DOM. It is so much easier if I could directly call the handler, but I'm probably just lazy :). On the other hand, I find this also an interesting case! Maybe I can start chrome with some options which make these debug functions available? – Jeanluca Scaljeri Apr 29 '19 at 16:15
  • https://stackoverflow.com/questions/2518421/jquery-find-events-handlers-registered-with-an-object seems this is what you are looking for – Ananthapadmanabhan Apr 29 '19 at 16:17
  • 1
    @Ananthu that topic is about `jQuery` – messerbill Apr 29 '19 at 16:41
  • 1
    https://stackoverflow.com/questions/446892/how-to-find-event-listeners-on-a-dom-node-when-debugging-or-from-the-javascript/3426352 Here is a javascript only way of getting things. It also seems like a bit over overhead to set all that up. answer by Aiden Waterman will get you started – Gauthier Apr 29 '19 at 16:59
  • Interesting. I wonder if you can modify the `addEventListener` function and then load the page. – Jeanluca Scaljeri Apr 29 '19 at 17:07
  • I've tested the suggested solution from @Gauthier and it works as long as I first change the url, than modify `EventTarget.prototype.addEventListener`: Like this: `browser.url('....');browser.execute(....)`. Thanks a lot! – Jeanluca Scaljeri Apr 29 '19 at 17:58
  • Hi, I have encountered similar issues and seems you finally have your answer. Could you please share a little bit more about how you solve the problem? https://stackoverflow.com/questions/74895101/how-to-access-event-listeners-of-element-using-selenium – JTT Dec 23 '22 at 01:53

0 Answers0