selenium-webdriver Handle an alert Selenium with Java


Here's how to Handle a popup alert in Java with Selenium:

There are 3 types of popups.

  1. Simple alert : alert("This is a simple alert");
  2. Confirmation alert : var popuResult = confirm("Confirm pop up with OK and Cancel button");
  3. Prompt alert : var person = prompt("Do you like stackoverflow?", "Yes/No");

Its upto user which type of popup need to be handled in their test case.

Either you can

  1. accept() To accept the alert

  2. dismiss() To dismiss the alert

  3. getText() To get the text of the alert

  4. sendKeys() To write some text to the alert

For simple alert:

    Alert simpleAlert = driver.switchTo().alert();
    String alertText = simpleAlert.getText();
    System.out.println("Alert text is " + alertText);

For Confirmation alert :

    Alert confirmationAlert = driver.switchTo().alert();
    String alertText = confirmationAlert.getText();
    System.out.println("Alert text is " + alertText);

For Prompt alert :

    Alert promptAlert  = driver.switchTo().alert();
    String alertText = promptAlert .getText();
    System.out.println("Alert text is " + alertText);
    //Send some text to the alert
    promptAlert .sendKeys("Accepting the alert");
    Thread.sleep(4000); //This sleep is not necessary, just for demonstration
    promptAlert .accept();

according to your needs.

Another way you can do this, is wrap your code inside a try-catch:

   // Your logic here.
} catch(UnhandledAlertException e){
  Alert alert = driver.switchTo().alert();
// Continue.