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 }}
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();}
Alert alert = driver.switchTo().alert();alert.accept();
You can also decline the alert box:
Alert alert = driver.switchTo().alert();alert().dismiss();