So, I was able to reproduce your problem using the sample HTML file below
<html> <body> Please enter a value for me: <input name="name" > <script> window.onbeforeunload = function(e) { return 'Dialog text here.'; }; </script> <h2>ask questions on exit</h2> </body> </html>
Then I ran a sample script that reproduces the hang
from selenium import webdriver driver = webdriver.Firefox() driver.get("http://localhost:8090/index.html") driver.find_element_by_name("name").send_keys("Tarun") driver.quit()
This will hang selenium python indefinitely. Which is not so good. The problem is that window.onload and window.onbeforeunload for Selenium are tough to handle due to the life cycle when this happens. onload occurs even before selenium has entered its own code to suppress alert and confirm for processing. I am sure that onbeforeunload also does not reach selenium.
So, there are several ways to get around.
Change application
Ask developers not to use onload or onbeforeunload . Will they listen? Not sure
Disable preload in profile
This is what you already posted in your answer
from selenium import webdriver profile = webdriver.FirefoxProfile()
Disable events through code
try: driver.execute_script("window.onunload = null; window.onbeforeunload=null") finally: pass driver.quit()
This will only work if you do not have several tabs that can be opened or the tab assumes that the popup is in focus. But this is a good general way to deal with this situation.
Do not allow selenium
Well, the reason selenium is because it sends a geckodriver request, which then sends it to firefox, and one of them just doesn't respond, as they wait for the user to close the dialog. But the problem is that the Selenium python driver does not set the timeout for this part of the connection.
To solve the problem, it is as simple as adding two lines of code below
import socket socket.setdefaulttimeout(10) try: driver.quit() finally:
But the problem with this approach is that the driver / browser will not be closed anyway. Here you need an even more robust approach to kill the browser, as described below.
In Python, how to check if Selenium WebDriver has left or not?
Code at the top of the link to complete the response
from selenium import webdriver import psutil driver = webdriver.Firefox() driver.get("http://tarunlalwani.com") driver_process = psutil.Process(driver.service.process.pid) if driver_process.is_running(): print ("driver is running") firefox_process = driver_process.children() if firefox_process: firefox_process = firefox_process[0] if firefox_process.is_running(): print("Firefox is still running, we can quit") driver.quit() else: print("Firefox is dead, can't quit. Let kill the driver") firefox_process.kill() else: print("driver has died")