Introduction
Handling browser pop-ups and alerts efficiently is one of the most important aspects of effective web automation. Alerts in Selenium WebDriver are interface components that demand immediate action before moving forward with the script execution. Since they are related to browser dialogue boxes and not regular HTML components, they can be handled using regular findElement methods. However, a tester has to use the Alert API to perform actions on such components.
Becoming a master in handling pop-ups and alerts helps your automated test suites continue uninterrupted. Get a head start in your journey to becoming a Selenium Automation Master. Download Your Free Selenium Course Syllabus here.
Handling Alerts in Selenium
In the world of automated testing, the web application is not always composed of static HTML elements. Sometimes the application interacts with the user using JavaScript Alerts, Confirmations, and Prompts. To a Selenium script, these pop-ups are “modal” roadblocks: they freeze the browser’s UI thread, and the script cannot interact with the underlying page until the alert is resolved.
As these alerts are browser-generated and not part of the DOM (Document Object Model) tree, they cannot be located using standard locators like id, name, or xpath. To deal with this situation, Selenium provides a special Alert API. Learn more with our Selenium training in Chennai.
1. Understanding the Types of Alerts
Before moving on to the code part of the problem, it is important to understand the different types of alerts you are likely to encounter while dealing with JavaScript in Selenium.
| Alert Type | Description | Available Actions |
| Simple Alert | Displays a message and an OK button. Used for notifications. | accept() |
| Confirmation Alert | Asks a question. Contains OK and Cancel buttons. | accept(), dismiss() |
| Prompt Alert | Requests user input via a text box. Contains OK and Cancel. | sendKeys(), accept(), dismiss() |
2. The Selenium Alert API
Before you can interact with the alert, you need to switch the focus of the driver to the alert box using the switchTo().alert() method of the Selenium WebDriver API.
Core Methods of the Alert Interface:
- accept(): This method simulates a click on the ‘OK’ or ‘Yes’ button.
- dismiss(): This method simulates a click on the ‘Cancel’ or ‘No’ button.
- getText(): This method gets the text of the alert.
- sendKeys(String text): This method simulates the sending of keys to the prompt box of the alert.
Explore our Selenium tutorial for beginners.
3. Handling Alerts: Step-by-Step with Code
A. Handling a Simple Alert
A simple alert just pops up, and you need to accept it.
// 1. Trigger the alert (e.g., clicking a button)
driver.findElement(By.id(“alertBtn”)).click();
// 2. Switch to the alert
Alert simpleAlert = driver.switchTo().alert();
// 3. Read the message
String alertMessage = simpleAlert.getText();
System.out.println(“Alert says: ” + alertMessage);
// 4. Accept the alert
simpleAlert.accept();
B. Handling a Confirmation Alert
With confirmation alerts, your test logic will likely involve both “positive” (Accept) and “negative” (Dismiss) cases.
driver.findElement(By.id(“confirmBtn”)).click();
Alert confirmAlert = driver.switchTo().alert();
// To reject the action:
confirmAlert.dismiss();
// Verification: Check if the UI reflects the cancellation
C. Handling a Prompt Alert
Prompt alerts are the most complicated, as data entry is required before the alert can be submitted.
driver.findElement(By.id(“promptBtn”)).click();
Alert promptAlert = driver.switchTo().alert();
// Enter text into the prompt
promptAlert.sendKeys(“Selenium Automation”);
// Accept to submit the text
promptAlert.accept();
4. Synchronization: Using Explicit Waits
NoAlertPresentException is one of the most common causes of flaky tests. This error occurs when your script attempts to switch to an alert before the browser has finished rendering it.
To ensure your tests are more reliable, always use WebDriverWait.
Example with Explicit Wait
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.util.Duration;
import org.openqa.selenium.support.ui.WebDriverWait;
// Initialize wait
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Wait until the alert is actually present on the screen
wait.until(ExpectedConditions.alertIsPresent());
// Now switch and interact
Alert alert = driver.switchTo().alert();
alert.accept();
Fine-tune your skills with our Selenium project ideas.
5. Alerts vs. Modal Dialogs
One common error is mixing up JavaScript Alerts and Bootstrap/HTML Modals.
| Feature | JavaScript Alert | HTML/Bootstrap Modal |
| Origin | Browser-level (OS styled) | DOM-level (CSS/HTML styled) |
| Inspection | Cannot be inspected (Right-click disabled) | Can be inspected like any other element |
| Selenium Handling | driver.switchTo().alert() | driver.findElement(By.id(…)) |
| Blocking | Blocks all interaction with the page | Can sometimes be non-blocking |
6. Troubleshooting Common Exceptions
- NoAlertPresentException: Thrown when switchTo().alert() is called, but no alert is visible.
- Solution: Use Explicit Waits.
- UnhandledAlertException: Thrown when an unexpected alert appears, and your driver attempts to perform a standard action, such as click(), on the page.
- Solution: Your logic should handle expected alerts, or use a try-catch block.
Get expertise with our Selenium interview questions and answers.
7. Best Practices for Professional Automation
- Always verify the text: It’s not enough just to dismiss the pop-up; use getText() to ensure that the proper text is being displayed to the user.
- Try-Catch for Optional Alerts: If an alert only shows up under certain circumstances, such as a cookie consent or location request, use try-catch to avoid test failures.
- Maximize Browser before Alert Interaction: The browser window size might be too small for some headless browsers, causing issues with displaying the alert.
Conclusion
Handling alerts is an important skill set that is required to ensure the stability of the test suites that you have created. By using the Alert API and implementing synchronization using Explicit Waits, you can easily overcome the issues that are caused by the pop-ups that interrupt the execution of the scripts running in the browsers. Are you looking to move from the world of manual testing to the high-paying world of automated testing? We have the expertise and the sessions to give you the practical knowledge you need to succeed.
Enroll with the best Software Training Institute in Chennai and gain expertise from the experts. Know the Upcoming Batches and Course Details.
