Alert handling in Selenium WebDriver (selenium 2) with Java

I want to determine if a warning has appeared or not. I am currently using the following code:

try { Alert alert = webDriver.switchTo().alert(); // check if alert exists // TODO find better way alert.getText(); // alert handling log().info("Alert detected: {}" + alert.getText()); alert.accept(); } catch (Exception e) { } 

The problem is that if there is no warning in the current state of the web page, it waits a certain amount of time before the timeout is reached, and then throws an exception, and therefore the performance is very poor.

Is there a better way, possibly an alert handler, that I can use for dynamically generated alerts?

+34
java selenium-webdriver popup alert
Nov 23. 2018-11-11T00:
source share
5 answers

This is what worked for me with Explicit Wait from here WebDriver: advanced use

 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 } } 
+68
Dec 05
source share

Write the following method:

 public boolean isAlertPresent() { try { driver.switchTo().alert(); return true; } // try catch (Exception e) { return false; } // catch } 

Now you can check for an alert or not using the method written above, as shown below:

 if (isAlertPresent()) { driver.switchTo().alert(); driver.switchTo().alert().accept(); driver.switchTo().defaultContent(); } 
+14
Apr 08 '13 at 8:08
source share
 Alert alert = driver.switchTo (). Alert ();

 alert.accept ();

You can also refuse the warning window:

 Alert alert = driver.switchTo (). Alert ();

 alert (). dismiss ();
+2
Feb 03 '15 at 8:25
source share
 try { //Handle the alert pop-up using seithTO alert statement Alert alert = driver.switchTo().alert(); //Print alert is present System.out.println("Alert is present"); //get the message which is present on pop-up String message = alert.getText(); //print the pop-up message System.out.println(message); alert.sendKeys(""); //Click on OK button on pop-up alert.accept(); } catch (NoAlertPresentException e) { //if alert is not present print message System.out.println("alert is not present"); } 
+2
Feb 13 '15 at 7:12
source share

You can try

  try{ if(webDriver.switchTo().alert() != null){ Alert alert = webDriver.switchTo().alert(); alert.getText(); //etc. } }catch(Exception e){} 

If this does not work, you can try to loop through all window handles and see if a warning exists. I am not sure if the warning will open in the form of a new window using selenium.

 for(String s: webDriver.getWindowHandles()){ //see if alert exists here. } 
0
Nov 23 '11 at 16:10
source share



All Articles