I am using a Chrome Driver and trying to test a webpage.
Normally it runs fine, but sometimes I get exceptions:
org.openqa.selenium.UnhandledAlertE
You can use Wait
functionality in Selenium WebDriver to wait for an alert, and accept it once it is available.
In C# -
public static void HandleAlert(IWebDriver driver, WebDriverWait wait)
{
if (wait == null)
{
wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
}
try
{
IAlert alert = wait.Until(drv => {
try
{
return drv.SwitchTo().Alert();
}
catch (NoAlertPresentException)
{
return null;
}
});
alert.Accept();
}
catch (WebDriverTimeoutException) { /* Ignore */ }
}
Its equivalent in Java -
public static void HandleAlert(WebDriver driver, WebDriverWait wait) {
if (wait == null) {
wait = new WebDriverWait(driver, 5);
}
try {
Alert alert = wait.Until(new ExpectedCondition{
return new ExpectedCondition() {
@Override
public Alert apply(WebDriver driver) {
try {
return driver.switchTo().alert();
} catch (NoAlertPresentException e) {
return null;
}
}
}
});
alert.Accept();
} catch (WebDriverTimeoutException) { /* Ignore */ }
}
It will wait for 5 seconds until an alert is present, you can catch the exception and deal with it, if the expected alert is not available.