11

Possible Duplicate:
selenium 2.4.0, how to check for presence of an alert

I am using the following code to close the alert window :

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

The alert appears a few seconds after the opening of the main window.

How can I wait and check if alert appears ?

Community
  • 1
  • 1
khris
  • 4,809
  • 21
  • 64
  • 94
  • refer my answer: https://stackoverflow.com/questions/42358965/how-to-handle-authentication-alert-of-browser-in-selenium-webdriver/59611252#59611252 – Shubham Jain Jan 06 '20 at 11:29

2 Answers2

15

No default method for waiting for alert.

but, you can write your own method something like this.

waitForAlert(WebDriver driver)
{
   int i=0;
   while(i++<5)
   {
        try
        {
            Alert alert = driver.switchTo().alert();
            break;
        }
        catch(NoAlertPresentException e)
        {
          Thread.sleep(1000);
          continue;
        }
   }
}
Aardvark
  • 8,474
  • 7
  • 46
  • 64
Santoshsarma
  • 5,627
  • 1
  • 24
  • 39
  • The client doesn't accept that we are using dead waits (Thread.sleep) he simply wouldn't accept the PR. Can't we replace it with expected conditions? – paul May 15 '19 at 18:40
-1
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;

 }
eugene.polschikov
  • 7,254
  • 2
  • 31
  • 44
  • 1
    This method will not wait for alert. Just it will check whether the alert is present or not . – Santoshsarma Sep 28 '12 at 13:14
  • sorry. yeah. got a lil but misconfused. try this: http://stackoverflow.com/questions/8310548/how-can-i-reliably-wait-for-javascript-alerts-using-selenium2-webdriver – eugene.polschikov Sep 28 '12 at 13:22