Chromedriver headless alerts

google-chrome-headlessselenium-chromedriverselenium-webdriver

I have this issue with selenium webdriver tests with chromedriver. Although I can run tests succesfully when using Chrome browser I can't run the same tests in headless mode.

I cannot handle the Js alerts. Actually when taking a screenshot it seems that the alert won't even pop-up.

Alert screenshot

I have tried several workarounds:

1) driver.window_handles –> No other window seems to be present

2) driver.execute_script("window.confirm = function(){return true;}") –> Nothing changed with that script

3) element = WebDriverWait(driver, 20).until(EC.alert_is_present()) and of course an explicit wait

In browser mode I use a plain:

try:
    print driver.switch_to.alert.text
    driver.switch_to.alert.accept()
except NoAlertPresentException as e: 
    print("no alert")

Anyone else having this issue with alerts in headless mode?

  • chromedriver v.2.30.477691
  • Chrome Version 59.0.3071.115

Best Answer

Still having this problem as of Chrome 61, so I spent a while looking for a different solution. My favorite because of it's simplicity is injecting javascript before the alert is shown in order to automatically accept the alert.

Just put the following line of code before the line that causes the alert to be shown:

driver.ExecuteJavaScript("window.confirm = function(){return true;}");

Works with both headless chrome and PhantomJS.

Related Topic