Alert handling in Selenium WebDriver (selenium 2) with Java
This is what worked for me using Explicit Wait from here WebDriver: Advanced Usage
public void checkAlert() {
try {
WebDriverWait wait = new WebDriverWait(driver, 2);
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
alert.accept();
} catch (Exception e) {
//exception handling
}
}
Alert alert = driver.switchTo().alert(); alert.accept();
You can also decline the alert box:
Alert alert = driver.switchTo().alert(); alert().dismiss();
Write the following method:
public boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} // try
catch (Exception e) {
return false;
} // catch
}
Now, you can check whether alert is present or not by using the method written above as below:
if (isAlertPresent()) {
driver.switchTo().alert();
driver.switchTo().alert().accept();
driver.switchTo().defaultContent();
}
try
{
//Handle the alert pop-up using seithTO alert statement
Alert alert = driver.switchTo().alert();
//Print alert is present
System.out.println("Alert is present");
//get the message which is present on pop-up
String message = alert.getText();
//print the pop-up message
System.out.println(message);
alert.sendKeys("");
//Click on OK button on pop-up
alert.accept();
}
catch (NoAlertPresentException e)
{
//if alert is not present print message
System.out.println("alert is not present");
}