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<Alert>{
return new ExpectedCondition<Alert>() {
@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.
You can try this snippet:
public void acceptAlertIfAvailable(long timeout)
{
long waitForAlert= System.currentTimeMillis() + timeout;
boolean boolFound = false;
do
{
try
{
Alert alert = this.driver.switchTo().alert();
if (alert != null)
{
alert.accept();
boolFound = true;
}
}
catch (NoAlertPresentException ex) {}
} while ((System.currentTimeMillis() < waitForAlert) && (!boolFound));
}
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();
}
}
The below code will help to handle unexpected alerts in selenium
try{
} catch (Exception e) {
if(e.toString().contains("org.openqa.selenium.UnhandledAlertException"))
{
Alert alert = getDriver().switchTo().alert();
alert.accept();
}
}