Wait for an Alert in Selenium WebDriver with Java

We might have come across the scenario, where we might need to wait until an alert is displayed on the web page and perform some actions. We exactly do not know how much time it takes for Alert to display on page.

In this case, we need to wait until Alert is displayed on the page.

Have a look at the below code snippet that achieves the same objective.

import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class WaitForAlert {
             public static void main(String[] args) throws Exception {

                          WebDriver driver = new FirefoxDriver();
                          driver.manage().window().maximize();

                         String url = “http://www.web-                                    source.net/web_design_tips/alert_message_web_page_load.htm”;
driver.get(url);

                         try{

                                     WebDriverWait wait = new WebDriverWait(driver, 5);
                                     wait.until(ExpectedConditions.alertIsPresent());

                                     Alert alert = driver.switchTo().alert();
                                     System.out.println(“Alert box text ” + alert.getText());
                                     alert.accept();

} catch (NoAlertPresentException noAlert) {
noAlert.getMessage();
}
           }
}

The below two lines in the code snippet wait for 5 seconds for the alert to pop up on the page. If alert is found on the web page, the execution goes on. Otherwise it will give NoAlertPresentException .

WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.alertIsPresent());\

Hope it works for you!!

Cheers 🙂

Advertisements

#wait-for-alert, #wait-until-alert-is-displayed, #wait-until-alertispresent