Skip to content
Advertisement

Adding JavaScript event listener with Selenium triggers it automatically

As there is (according to my research) no way to catch user input with selenium, I am trying to use a JavaScript event listener.

But when I add the event listener by executing the JavaScript code, the function is automatically triggered without me (as the user) doing anything. Furthermore, there is no way to trigger the function again.

Does anyone know what the problem might be and how I could solve it? FYI: My code is in Python 3.8

Thank you in advance, Raphael

# this is a self defined function that creates a new selenium WebDriver
browser = gf.create_browser(headless=False)

browser.get("https://www.google.com")

browser.execute_script('document.getElementById("hplogo").addEventListener("mouseover",console.log("Success"))')

time.sleep(90)

The console displays “success” as soon as the script is executed, afterwards the event is never triggered again. I have tried different events (click, mouseover,…), different functions and different websites with different elemtents.

Advertisement

Answer

You’re not passing a function – you’re actually just directly calling it

console.log("Success")

This ^ calls the function. The actually parameter you end up passing is the result of console.log, not the function itself (which if I remember is just an undefined). If you want to actually pass a function, you should make something like this.

() => console.log("Success")

For pre ES6 supported browsers, you can use:

function(){console.log("Success")}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement