How to check if a warning exists using WebDriver?

I need to check for Alert in WebDriver.

Sometimes a pop-up warning appears, but sometimes it does not appear. I need to check if a warning exists, but I can accept or reject it or it will say: no alerts were found.

+64
selenium webdriver alert
Jul 13 '12 at 9:12
source share
6 answers
public boolean isAlertPresent() { try { driver.switchTo().alert(); return true; } // try catch (NoAlertPresentException Ex) { return false; } // catch } // isAlertPresent() 

check the link here https://groups.google.com/forum/?fromgroups#!topic/webdriver/1GaSXFK76zY

+79
Jul 13 2018-12-12T00:
source share

The following (a C # implementation, but similar to Java) allows you to determine if a warning exists without exception and without creating a WebDriverWait object.

 boolean isDialogPresent(WebDriver driver) { IAlert alert = ExpectedConditions.AlertIsPresent().Invoke(driver); return (alert != null); } 
+23
Jun 16 '15 at 22:04
source share

I would suggest using ExpectedConditions and alertIsPresent () . ExpectedConditions is a wrapper class that implements the useful conditions defined in the ExpectedCondition interface.

 WebDriverWait wait = new WebDriverWait(driver, 300 /*timeout in seconds*/); if(wait.until(ExpectedConditions.alertIsPresent())==null) System.out.println("alert was not present"); else System.out.println("alert was present"); 
+10
Jul 16 2018-12-12T00:
source share

I found that the exception was catching driver.switchTo().alert(); so slow in Firefox (FF V20 and selenium-java-2.32.0).

So, I choose another way:

  private static boolean isDialogPresent(WebDriver driver) { try { driver.getTitle(); return false; } catch (UnhandledAlertException e) { // Modal dialog showed return true; } } 

And this is the best way when in most of your test cases there is no NO dialog box (throwing an exception is expensive).

+7
Aug 12 '13 at 8:21
source share

I would suggest using ExpectedConditions and alertIsPresent () . ExpectedConditions is a wrapper class that implements the useful conditions defined in the 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 nilesh's answer, but adapted to catch a TimeoutException that is raised by the wait.until () method.

+5
Jul 16 '15 at 11:34
source share

public boolean isAlertPresent () {

 try { driver.switchTo().alert(); system.out.println(" Alert Present"); } catch (NoAlertPresentException e) { system.out.println("No Alert Present"); } 

}

+1
Dec 17 '17 at 5:21
source share



All Articles