Alert Handling in Selenium

Profile picture for user arilio666

In Selenium, alerts are handled using the Alert interface. To handle an alert, you can first switch to the alert using the switchTo() method on the 

WebDriver, and then interact with it using the accept(), dismiss(), or sendKeys() methods, depending on what you need to do. Here's an example:

 

// switch to the alert
Alert alert = driver.switchTo().alert();

// accept the alert (e.g., click the "OK" button)
alert.accept();

// or dismiss the alert (e.g., click the "Cancel" button)
alert.dismiss();

// or send keys to the alert
alert.sendKeys("text to send");

 

Please be aware that switchTo().alert() may throw a NoAlertPresentException if no alert is present. You should add a try-catch statement to handle it.

 

try {
  Alert alert = driver.switchTo().alert();
  alert.accept();
} catch (NoAlertPresentException noAlert) {
  // There is no alert present
}

 

You can also use switchTo().alert().getText() to get the text of the alert to check whether the alert is the one you want to handle before doing any actions.

 

Example:

 

We will be using the autopract site to handle alerts.

 

 

import org.openqa. Selenium.Alert;
import org.openqa. Selenium.By;
import org.openqa. Selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class PopUp {

public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
WebDriverManager.chromedriver().setup();
ChromeDriver driver = new ChromeDriver();
driver.get("http://autopract.com/selenium/alert5/");
driver.manage().window().maximize();
driver.findElement(By.xpath("//button[@id=\"alert-button\"]")).click();
Alert alert = driver.switchTo().alert();
alert.accept();
Thread.sleep(8000);
driver.findElement(By.xpath("//button[@id=\"confirm-button\"]")).click();
alert.dismiss();
Thread.sleep(8000);
driver.findElement(By.xpath("//button[@id=\"prompt-button\"]")).click();
alert.sendKeys("310814205013");
alert.accept();
}
}

 

Here we handled three alerts, which also involved sending keys to alerts.