I need to check the existence of Alert in WebDriver.
Sometimes it pops up an alert but sometimes it will not pop up. I need to check if the alert exists first, then
I would suggest to use ExpectedConditions and alertIsPresent(). ExpectedConditions is a wrapper class that implements useful conditions defined in ExpectedCondition interface.
public boolean isAlertPresent(){
boolean foundAlert = false;
WebDriverWait wait = new WebDriverWait(driver, 0 /*timeout in seconds*/);
try {
wait.until(ExpectedConditions.alertIsPresent());
foundAlert = true;
} catch (TimeoutException eTO) {
foundAlert = false;
}
return foundAlert;
}
Note: this is based on the answer by nilesh, but adapted to catch the TimeoutException which is thrown by the wait.until() method.
public boolean isAlertPresent() {
try
{
driver.switchTo().alert();
system.out.println(" Alert Present");
}
catch (NoAlertPresentException e)
{
system.out.println("No Alert Present");
}
}
The following (C# implementation, but similar in Java) allows you to determine if there is an alert without exceptions and without creating the WebDriverWait
object.
boolean isDialogPresent(WebDriver driver) {
IAlert alert = ExpectedConditions.AlertIsPresent().Invoke(driver);
return (alert != null);
}
This code will check whether the alert is present or not.
public static void isAlertPresent(){
try{
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText()+" Alert is Displayed");
}
catch(NoAlertPresentException ex){
System.out.println("Alert is NOT Displayed");
}
}
public static void handleAlert(){
if(isAlertPresent()){
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
}
}
public static boolean isAlertPresent(){
try{
driver.switchTo().alert();
return true;
}catch(NoAlertPresentException ex){
return false;
}
}
ExpectedConditions
is obsolete, so:
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.AlertIsPresent());
C# Selenium 'ExpectedConditions is obsolete'