org.openqa.selenium.UnhandledAlertException: unexpected alert open

I had this problem too. It was due to the default behaviour of the driver when it encounters an alert. The default behaviour was set to “ACCEPT”, thus the alert was closed automatically, and the switchTo().alert() couldn’t find it.

The solution is to modify the default behaviour of the driver (“IGNORE”), so that it doesn’t close the alert:

DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
d = new FirefoxDriver(dc);

Then you can handle it:

try {
    click(myButton);
} catch (UnhandledAlertException f) {
    try {
        Alert alert = driver.switchTo().alert();
        String alertText = alert.getText();
        System.out.println("Alert data: " + alertText);
        alert.accept();
    } catch (NoAlertPresentException e) {
        e.printStackTrace();
    }
}

Leave a Comment