Mastering Alert Handling in Selenium WebDriver – A Complete Guide
When automating web applications, handling JavaScript alerts and pop-ups is essential. Selenium WebDriver provides built-in methods to interact with different types of alerts that appear while executing test scripts.
This guide will cover:
✅ Types of alerts in Selenium
✅ How to handle them with examples
✅ Best practices for dealing with alerts
πΉ What Are Alerts in Selenium?
Alerts are pop-ups that appear on a webpage and block user interaction until they are dismissed. They are commonly used for:
✔ Displaying information or warnings
✔ Asking users for confirmation (OK/Cancel)
✔ Taking user input
In Selenium, alerts are part of JavaScript pop-ups, and they must be handled using the Alert
interface.
πΉ Alert Methods in Selenium WebDriver
Selenium WebDriver provides several methods to handle JavaScript alerts and pop-ups using the Alert
interface. Below is a complete list of methods along with explanations and examples.
π 1. accept()
– Clicks "OK" on the Alert
✔ Used to accept an alert when a pop-up appears.
✔ Equivalent to clicking the "OK" button.
✅ Example:
Alert alert = driver.switchTo().alert();
alert.accept(); // Clicks OK
π‘ Use Case: Handling confirmation alerts like "Are you sure you want to proceed?"
π 2. dismiss()
– Clicks "Cancel" on the Alert
✔ Used to dismiss an alert.
✔ Equivalent to clicking the "Cancel" button.
✅ Example:
Alert alert = driver.switchTo().alert();
alert.dismiss(); // Clicks Cancel
π‘ Use Case: Useful for dismissing confirmation pop-ups when the user does not want to proceed.
π 3. getText()
– Retrieves the Alert Message
✔ Fetches the text message displayed on the alert.
✔ Useful for verification in test cases.
✅ Example:
Alert alert = driver.switchTo().alert();
String alertMessage = alert.getText();
System.out.println("Alert Message: " + alertMessage);
alert.accept();
π‘ Use Case: Validating warning messages like "This action cannot be undone."
π 4. sendKeys(String text)
– Enters Text in a Prompt Alert
✔ Used to send text input to a Prompt Alert (an alert with a text box).
✅ Example:
Alert alert = driver.switchTo().alert();
alert.sendKeys("Selenium Automation"); // Enter text
alert.accept(); // Click OK
π‘ Use Case: Handling alerts that require user input, such as "Enter your name:"
π 5. isAlertPresent()
– Checks If an Alert Exists
✔ Helps avoid NoAlertPresentException
if an alert is not present.
✅ Example:
public boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true; // Alert is present
} catch (NoAlertPresentException e) {
return false; // No alert found
}
}
π‘ Use Case: Ensuring an alert exists before attempting to handle it.
π 6. waitForAlert()
– Explicit Wait for Alert
✔ Useful when alerts appear dynamically with a delay.
✅ Example:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
alert.accept();
π‘ Use Case: Handling alerts that appear after performing an action like form submission.
π Summary of Alert Methods in Selenium
Method | Description | Use Case |
---|---|---|
accept() |
Clicks "OK" on the alert | Confirming actions |
dismiss() |
Clicks "Cancel" on the alert | Canceling actions |
getText() |
Retrieves text from the alert | Validating messages |
sendKeys(String text) |
Enters text in a prompt alert | Inputting data |
isAlertPresent() |
Checks if an alert is present | Avoiding exceptions |
waitForAlert() |
Waits for an alert to appear | Handling dynamic alerts |
πΉ Types of Alerts in Selenium
Selenium deals with three types of alerts:
Type of Alert |
Description |
---|---|
Simple Alert |
Displays a message with an OK button. |
Confirmation Alert |
Displays a message with OK and Cancel buttons. |
Prompt Alert |
Displays a message with an input box, OK, and Cancel buttons. |
πΉ How to Handle Alerts in Selenium?
To interact with alerts, Selenium provides the switchTo().alert()
method. This allows the WebDriver to switch focus to the alert box and perform actions like accepting, dismissing, reading text, or entering values.
1️⃣ Handling Simple Alert in Selenium
A Simple Alert contains only an OK button. It is typically used to show messages or warnings.
✅ Example: Accepting a Simple Alert
// Switch to the alert
Alert simpleAlert = driver.switchTo().alert();
// Get the alert text
System.out.println("Alert message: " + simpleAlert.getText());
// Click OK to accept the alert
simpleAlert.accept();
πΉ Use Case: Useful when alerts display messages like "Action completed successfully".
2️⃣ Handling Confirmation Alert in Selenium
A Confirmation Alert requires the user to either accept or dismiss the message by clicking OK or Cancel.
✅ Example: Accepting and Dismissing a Confirmation Alert
// Switch to the alert
Alert confirmAlert = driver.switchTo().alert();
// Get the text of the alert
System.out.println("Confirmation Alert message: " + confirmAlert.getText());
// Click OK (Accept)
confirmAlert.accept();
// OR Click Cancel (Dismiss)
// confirmAlert.dismiss();
πΉ Use Case: Used in delete actions, such as "Are you sure you want to delete this record?".
3️⃣ Handling Prompt Alert in Selenium
A Prompt Alert allows users to enter text in an input box before clicking OK or Cancel.
✅ Example: Entering Text in a Prompt Alert
// Switch to the alert
Alert promptAlert = driver.switchTo().alert();
// Get the alert text
System.out.println("Prompt Alert message: " + promptAlert.getText());
// Enter text into the prompt alert's input field
promptAlert.sendKeys("Selenium Automation");
// Click OK
promptAlert.accept();
// OR Click Cancel
// promptAlert.dismiss();
πΉ Use Case: Used in login pop-ups or input-based alerts, such as "Enter your name to continue".
πΉ Checking If an Alert Is Present
Sometimes, an alert might not be present, and trying to switch to it will cause an exception. To avoid this, we can check if an alert exists using the following method:
✅ Example: Safe Alert Handling
public boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
πΉ Use Case: Prevents script failures when alerts appear dynamically.
πΉ Dismissing Unwanted Alerts Using try-catch
In real-world automation, alerts may appear unexpectedly. If an alert appears and is not handled, Selenium throws an UnhandledAlertException
.
✅ Example: Handling Unexpected Alerts
try {
Alert unexpectedAlert = driver.switchTo().alert();
System.out.println("Unexpected Alert: " + unexpectedAlert.getText());
unexpectedAlert.dismiss();
} catch (NoAlertPresentException e) {
System.out.println("No unexpected alert present.");
}
πΉ Use Case: Useful when pop-ups appear unexpectedly due to JavaScript execution.
πΉ Handling Authentication Pop-ups (Basic Authentication)
Some web applications require a username and password before accessing certain pages. These authentication pop-ups cannot be handled using the Alert
class, but they can be managed using URL encoding.
✅ Example: Handling Basic Authentication Pop-ups
// Format: https://username:password@websiteURL
driver.get("https://admin:password@mysecurewebsite.com");
πΉ Use Case: Used for handling authentication dialogs in applications requiring login credentials before accessing a page.
π Best Practices for Handling Alerts in Selenium
✔ Always switch to the alert before interacting with it.
✔ Use getText()
to verify the alert message before accepting/dismissing.
✔ Use sendKeys()
only for Prompt Alerts.
✔ Check if an alert is present before switching to avoid exceptions.
✔ Avoid using Thread.sleep()
for handling alerts. Instead, use Explicit Wait if alerts appear dynamically.
π Conclusion
Alert handling in Selenium WebDriver is crucial for automating JavaScript pop-ups efficiently.
By using accept(), dismiss(), and sendKeys(), we can manage all types of alerts and pop-ups effectively.
✅ Use accept()
to click OK
✅ Use dismiss()
to click Cancel
✅ Use sendKeys()
for entering text in Prompt Alerts
✅ Check if an alert exists before handling it
By mastering these techniques, your Selenium automation scripts will be more stable and efficient! π