Pages

Saturday 19 May 2012

How to check the presence of Alert (isAlertPresent) using WebDriver?

Below method will return true if the alert got displayed:

public boolean isAlertPresent() {

  boolean presentFlag = false;

  try {

   // Check the presence of alert
   Alert alert = driver.switchTo().alert();
   // Alert present; set the flag
   presentFlag = true;
   // if present consume the alert
   alert.accept();

  } catch (NoAlertPresentException ex) {
   // Alert not present
   ex.printStackTrace();
  }

  return presentFlag;

 }
Note - Thank you Ganesh S for asking this query.