Alert Handling in Selenium

Alert is a pop up that indicates some information or requests input from the user. When it’s displayed, the user can’t perform any action on the web page. Trying to interact with any element on the webpage while an alert is present will result in UnhandledAlertException: Modal dialog present.

There are three types of alerts:

1. Simple Alert

The purpose of these alerts is to display some information to the user. They only have an OK button.

Simple Alert

2.Confirmation Alert

These alerts will provide an option to the user to accept or dismiss the alert depending on user preference.

Confirmation Alert

3.Prompt Alert

Such alerts are displayed if user input is required in the alert box.

Prompt Alert

To handle alerts in selenium, we need to import org.openqa.selenium.Alert which provides Alert interface having the following important methods:

  • accept()

This method is used if we want to accept the alert (simple/confirmation/prompt alert). Usage example below:

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

 alert.accept();

  • dismiss()

This method is used if we want to dismiss the alert (confirmation/prompt alert). Usage example below:

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

 alert.dismiss();

  • getText()

This method is used if we want to get the text of the alert. Usage example below:

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

 String text = alert.getText();

System.out.println(“alert text is:”+text);

  • sendKeys()

This method is used if we want to type text in the prompt alert box. Usage example below:

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

alert.sendKeys(“Mayank”);

This will input ‘Mayank’ text to the alert box.

Also Read: Understanding Selenium WebDriver API Commands (Part 1)Understanding Selenium WebDriver API Commands (Part 2), and Understanding Selenium WebDriver API Commands (Part 3).