Alerts in Selenium WebDriver
Alerts are browser-level popup messages that appear when a web application needs to display information, request confirmation, or collect a small amount of text input from the user. In Selenium WebDriver, JavaScript alerts, confirmation dialogs, and prompt dialogs are handled through the Alert interface.
Selenium WebDriver provides methods to switch from the web page to the active browser alert, read its text, accept it, dismiss it, and enter text into prompt dialogs. Native JavaScript dialogs are different from normal HTML elements because they are not part of the page DOM. Selenium therefore provides a dedicated API for handling them.
JustAcademy Selenium Training: JustAcademy Selenium Training Course
JustAcademy Demo Registration: Register for Selenium Course Demo
1. What is an Alert?
An alert is a browser-level dialog displayed by a web application to communicate with the user. A basic JavaScript alert normally contains a message and an OK button. Selenium cannot interact with such a dialog using normal WebElement methods because the alert is not an HTML element inside the page DOM.
JavaScript:
alert("Welcome to Selenium");
When this JavaScript executes, the browser displays a native dialog. Selenium must switch to this alert before reading or interacting with it.
2. Why Do We Need Alert Handling in Selenium?
Alerts can interrupt normal browser interaction. If an alert is open and Selenium tries to interact with the underlying page without handling the alert, the operation may fail because the browser is waiting for the alert to be handled.
Alert handling is required to:
- Read alert messages.
- Click the OK button.
- Click the Cancel button on confirmation dialogs.
- Enter text into prompt dialogs.
- Validate alert messages.
- Continue test execution after handling the popup.
- Prevent unexpected alert-related test failures.
3. JavaScript Alerts and Selenium
Selenium WebDriver provides an API for interacting with the three common JavaScript dialog types: alert, confirm, and prompt. These dialogs are browser-native popups rather than normal HTML elements.
| Dialog Type | Purpose | Typical Buttons | Text Input |
| Alert | Displays information or a warning | OK | No |
| Confirm | Requests confirmation | OK / Cancel | No |
| Prompt | Requests user input | OK / Cancel | Yes |
4. Types of JavaScript Alerts
The three primary JavaScript dialog types handled by Selenium are:
- Simple Alert
- Confirmation Alert
- Prompt Alert
Each type has a different purpose and requires slightly different Selenium operations.
5. Simple Alert
A simple alert displays a message and normally provides an OK button. It is commonly used for informational messages, warnings, successful operations, or validation messages.
window.alert("Registration completed successfully");
In Selenium, the alert is accessed using:
Alert alert = driver.switchTo().alert();
6. Confirmation Alert
A confirmation dialog asks the user to confirm or cancel an action. It generally contains two buttons: OK and Cancel.
window.confirm("Are you sure you want to delete this record?");
Use accept() to select OK and dismiss() to select Cancel.
7. Prompt Alert
A prompt dialog allows the user to enter text. Selenium can enter text into a prompt using the sendKeys() method of the Alert interface.
window.prompt("Enter your name");
The normal Selenium sequence is:
Alert alert = driver.switchTo().alert();
alert.sendKeys("Manish");
alert.accept();
8. Alert Interface
Selenium provides the org.openqa.selenium.Alert interface for handling JavaScript dialogs.
import org.openqa.selenium.Alert;
The Alert interface provides methods for retrieving alert text, accepting the dialog, dismissing it, and entering text into a prompt.
9. Switch to Alert
Before interacting with a JavaScript alert, Selenium needs to switch the WebDriver's focus to the active alert.
Alert alert = driver.switchTo().alert();
The switchTo().alert() method returns the currently active alert.
10. Accept an Alert
The accept() method clicks the positive or OK button of the alert.
Alert alert = driver.switchTo().alert();
alert.accept();
This is commonly used for simple alerts and for confirming an action in confirmation dialogs.
11. Dismiss an Alert
The dismiss() method closes the alert by selecting the Cancel option when the dialog provides one.
Alert alert = driver.switchTo().alert();
alert.dismiss();
It is especially useful for testing negative or cancellation scenarios.
12. Get Alert Text
The getText() method retrieves the message displayed by the alert.
Alert alert = driver.switchTo().alert();
String message = alert.getText();
System.out.println(message);
This is useful when the test needs to verify that the application displayed the correct message.
13. Send Text to a Prompt
The sendKeys() method can be used with a prompt dialog that contains an input field.
Alert alert = driver.switchTo().alert();
alert.sendKeys("Selenium");
alert.accept();
The text is entered into the prompt before accepting it.
14. Complete Alert Handling Sequence
A common Selenium alert-handling sequence is:
1. Perform an action that triggers the alert
2. Wait for the alert if necessary
3. Switch to the alert
4. Read the alert text if required
5. Accept, dismiss, or enter text
6. Continue interacting with the web page
15. Basic Alert Example in Selenium Java
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class AlertExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
driver.findElement(By.id("alertButton")).click();
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
driver.quit();
}
}
16. Handling a Simple Alert
driver.findElement(By.id("simpleAlert")).click();
Alert alert = driver.switchTo().alert();
String message = alert.getText();
System.out.println("Alert Message: " + message);
alert.accept();
The test first triggers the alert, switches to it, retrieves the message, and accepts it.
17. Handling a Confirmation Alert
driver.findElement(By.id("confirmButton")).click();
Alert alert = driver.switchTo().alert();
String message = alert.getText();
System.out.println(message);
alert.accept();
The same confirmation dialog can be tested with Cancel:
driver.findElement(By.id("confirmButton")).click();
Alert alert = driver.switchTo().alert();
alert.dismiss();
18. Handling a Prompt Alert
driver.findElement(By.id("promptButton")).click();
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.sendKeys("Selenium Automation");
alert.accept();
19. Alert Handling with Explicit Wait
For dynamic applications, the alert may not appear immediately after clicking a button. In such cases, an explicit wait can be used with alertIsPresent().
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
driver.findElement(By.id("alertButton")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
System.out.println(alert.getText());
alert.accept();
20. ExpectedConditions.alertIsPresent()
alertIsPresent() waits until an alert is present and returns the active Alert object.
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
This is generally more reliable than immediately calling driver.switchTo().alert() when the alert is generated asynchronously.
21. Why Explicit Wait is Useful for Alerts
Modern web applications can trigger dialogs after an API response, JavaScript operation, form validation, or asynchronous event. The alert may therefore appear after a small delay.
A fixed delay such as Thread.sleep() does not adapt to the actual application state. An explicit wait checks for the required condition until it becomes true or the timeout expires.
22. AlertNotPresent Scenario
If Selenium attempts to switch to an alert when no alert is currently present, an alert-related exception can occur.
Alert alert = driver.switchTo().alert();
For dynamic alerts, prefer:
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
23. Alert Text Validation
Alert messages can be validated using assertions. This is useful when the alert contains an important business message.
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String actualMessage = alert.getText();
Assert.assertEquals(actualMessage, "Registration completed successfully");
alert.accept();
24. Alert Validation with TestNG
import org.testng.Assert;
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String actualMessage = alert.getText();
Assert.assertEquals(actualMessage, "Are you sure?");
alert.accept();
25. Accept vs Dismiss
| Method | Purpose | Typical Use |
| accept() | Accepts the dialog | OK / Confirm |
| dismiss() | Dismisses or cancels the dialog | Cancel |
| getText() | Reads dialog message | Validation |
| sendKeys() | Enters text into a prompt | User input |
26. Alert vs WebElement
A common Selenium mistake is trying to locate a native JavaScript alert using findElement(). A native alert is not a normal DOM element.
| Alert | WebElement |
| Browser-level JavaScript dialog | HTML element |
| Handled using Alert interface | Handled using WebElement |
| Use switchTo().alert() | Use findElement() |
| Use accept(), dismiss(), getText(), sendKeys() | Use click(), sendKeys(), getText(), etc. |
| Not located with XPath | Can be located using XPath/CSS/etc. |
27. Can We Use XPath for a Native Alert?
No. A native JavaScript alert is not a normal HTML element in the page DOM, so XPath or CSS selectors cannot be used to locate its OK or Cancel buttons.
Selenium interacts with the dialog through the Alert API.
28. JavaScript Alert Example
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("alert('Hello Selenium');");
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
29. JavaScript Confirm Example
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("confirm('Are you sure?');");
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.dismiss();
30. JavaScript Prompt Example
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("prompt('Enter your name');");
Alert alert = driver.switchTo().alert();
alert.sendKeys("Manish");
alert.accept();
31. Alert Handling Flow
Start Test
|
v
Open Web Application
|
v
Perform Action
|
v
JavaScript Alert Appears
|
v
Wait for Alert
|
v
Switch to Alert
|
+----> Read Text
|
+----> Enter Text for Prompt
|
+----> Accept
|
+----> Dismiss
|
v
Return to Web Page
|
v
Continue Test
|
v
End Test
32. Alert Handling with Page Object Model
In a Page Object Model framework, alert handling can be placed in a reusable utility or page method when the alert belongs to a specific page workflow.
public String getAlertMessage() {
Alert alert = driver.switchTo().alert();
return alert.getText();
}
public void acceptAlert() {
Alert alert = driver.switchTo().alert();
alert.accept();
}
public void dismissAlert() {
Alert alert = driver.switchTo().alert();
alert.dismiss();
}
33. Reusable Alert Utility
public class AlertHelper {
private WebDriver driver;
public AlertHelper(WebDriver driver) {
this.driver = driver;
}
public Alert switchToAlert() {
return driver.switchTo().alert();
}
public String getText() {
return switchToAlert().getText();
}
public void accept() {
switchToAlert().accept();
}
public void dismiss() {
switchToAlert().dismiss();
}
public void sendKeys(String text) {
switchToAlert().sendKeys(text);
}
}
34. Wait Utility for Alerts
public Alert waitForAlert() {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
return wait.until(ExpectedConditions.alertIsPresent());
}
This approach centralizes alert synchronization and reduces duplicate code in test cases.
35. Handling Alert in a Login Test
Suppose an application displays an alert when invalid credentials are entered.
driver.findElement(By.id("username")).sendKeys("wrongUser");
driver.findElement(By.id("password")).sendKeys("wrongPassword");
driver.findElement(By.id("loginButton")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String message = alert.getText();
Assert.assertEquals(message, "Invalid username or password");
alert.accept();
36. Handling Alert in Registration
Registration forms may display a success alert after successful submission.
driver.findElement(By.id("registerButton")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String message = alert.getText();
Assert.assertEquals(message, "Registration successful");
alert.accept();
37. Handling Delete Confirmation
Delete operations are common scenarios for confirmation dialogs.
driver.findElement(By.id("deleteButton")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String message = alert.getText();
Assert.assertEquals(message, "Are you sure you want to delete?");
alert.accept();
38. Testing the Cancel Operation
Negative test cases should verify that Cancel prevents the intended operation when appropriate.
driver.findElement(By.id("deleteButton")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.dismiss();
39. Testing Prompt Input
driver.findElement(By.id("namePrompt")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.sendKeys("Selenium User");
alert.accept();
String result = driver.findElement(By.id("result")).getText();
Assert.assertEquals(result, "Selenium User");
40. Alert Text Before Accept
Always retrieve the message before accepting or dismissing the alert if the message needs to be validated.
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String message = alert.getText();
System.out.println("Message: " + message);
alert.accept();
41. Alert Object Lifecycle
An Alert object represents the currently active browser dialog. After accepting or dismissing the dialog, the dialog is closed. Test code should therefore obtain or use the alert reference appropriately for the active dialog.
Alert alert = driver.switchTo().alert();
String text = alert.getText();
alert.accept();
42. Multiple Alerts in a Workflow
If an application displays multiple alerts sequentially, each alert must be handled before Selenium can continue to the next operation.
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.accept();
alert = wait.until(ExpectedConditions.alertIsPresent());
alert.accept();
The exact behavior depends on the application and how the dialogs are triggered.
43. Alert and Synchronization
Alert handling is closely related to synchronization. The test should synchronize with the alert's appearance rather than assuming that the dialog appears immediately after a click.
driver.findElement(By.id("submit")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.accept();
44. Thread.sleep() with Alerts
A fixed delay can technically be used, but it is generally not the preferred synchronization strategy.
Thread.sleep(3000);
Alert alert = driver.switchTo().alert();
alert.accept();
The problem is that three seconds may be unnecessarily long when the alert appears quickly, and may still be insufficient when the application takes longer.
45. Better Alternative to Thread.sleep()
Alert alert = new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.alertIsPresent());
alert.accept();
This waits for the actual condition rather than waiting for an arbitrary amount of time.
46. Alert Handling with FluentWait
FluentWait can be used when customized timeout and polling behavior is required.
Wait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(10))
.pollingEvery(Duration.ofMillis(500))
.ignoring(NoSuchElementException.class);
Alert alert = wait.until(driver -> {
try {
return driver.switchTo().alert();
} catch (NoAlertPresentException e) {
return null;
}
});
alert.accept();
47. Common Alert Exceptions
| Exception | Possible Cause | Solution |
| NoAlertPresentException | No active alert exists | Wait for alert or verify trigger |
| UnhandledAlertException | Unexpected alert remains open | Handle the alert before continuing |
| TimeoutException | Alert did not appear within timeout | Verify trigger, locator, application state, and timeout |
| WebDriverException | Browser/driver interaction issue | Check browser, driver, session, and test state |
48. NoAlertPresentException
NoAlertPresentException occurs when Selenium tries to interact with an alert while no alert is currently present.
try {
Alert alert = driver.switchTo().alert();
alert.accept();
} catch (NoAlertPresentException e) {
System.out.println("No alert is currently present.");
}
Exception handling should not be used as a substitute for proper synchronization. For expected dynamic alerts, an explicit wait is usually more appropriate.
49. UnhandledAlertException
An unhandled alert can prevent Selenium from performing normal browser operations. If an alert unexpectedly remains open, the next WebDriver command may fail until the dialog is handled.
Alert alert = driver.switchTo().alert();
alert.accept();
Tests should identify whether the alert is expected and handle it at the appropriate point in the workflow.
50. TimeoutException for Alert
If alertIsPresent() waits until its timeout and no alert appears, a TimeoutException can occur.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
Investigate whether the triggering button was clicked correctly, whether the alert condition is actually expected, and whether the application changed its behavior.
51. Native Alert vs HTML Modal
Not every popup that looks like an alert is a JavaScript alert. Modern web applications frequently use HTML/CSS modal dialogs.
| Native JavaScript Alert | HTML/CSS Modal |
| Browser-level dialog | Part of the webpage DOM |
| Handled using Alert | Handled using WebElement |
| Cannot use XPath for buttons | Can use XPath/CSS selectors |
| Use accept/dismiss/sendKeys | Use click/sendKeys/getText etc. |
52. How to Identify a JavaScript Alert
If browser automation pauses and a native browser dialog appears outside the page DOM, it may be a JavaScript alert. In DevTools, normal HTML modal elements can generally be inspected as DOM nodes, whereas native JavaScript dialogs are handled by the browser and Selenium's Alert interface.
53. HTML Modal Example
<div id="confirmationModal">
<h2>Delete Record</h2>
<p>Are you sure?</p>
<button id="confirmDelete">Yes</button>
<button id="cancelDelete">No</button>
</div>
This is not a native JavaScript alert. It should be handled using normal WebElement methods.
driver.findElement(By.id("confirmDelete")).click();
54. Native Alert Example
<script>
function showAlert() {
alert("Record deleted successfully");
}
</script>
This creates a native JavaScript alert and should be handled using the Alert interface.
55. Alert vs Popup
The word popup is often used generally, but Selenium automation requires identifying what kind of popup is actually present.
| Popup Type | Selenium Approach |
| JavaScript Alert | Alert interface |
| JavaScript Confirm | Alert interface |
| JavaScript Prompt | Alert interface |
| HTML Modal | WebElement |
| Browser Tab/Window | Window handles |
| iframe | Switch to frame |
| Browser authentication dialog | Depends on browser/application/authentication mechanism |
56. Alert Handling Best Practices
- Use Alert for native JavaScript dialogs.
- Use explicit waits for dynamically appearing alerts.
- Read alert text before accepting or dismissing when validation is required.
- Use accept() for OK/confirmation actions.
- Use dismiss() for Cancel actions.
- Use sendKeys() only when working with prompt dialogs.
- Do not try to locate native alerts with XPath.
- Do not assume every visual popup is a JavaScript alert.
- Keep alert-handling logic reusable in automation frameworks.
- Use meaningful assertions for important alert messages.
57. Common Mistake: Using findElement()
driver.findElement(By.id("alert")).click();
The above code may be correct for the button that triggers the alert, but it cannot be used to locate the native alert itself.
Correct approach:
Alert alert = driver.switchTo().alert();
58. Common Mistake: Accepting Before Reading Text
If the test needs to validate the message, do not close the alert before retrieving its text.
Alert alert = driver.switchTo().alert();
String message = alert.getText();
Assert.assertEquals(message, "Operation completed");
alert.accept();
59. Common Mistake: Assuming Alert Appears Immediately
A click that triggers an alert may execute asynchronous JavaScript. Immediately switching to the alert can therefore cause a failure.
Prefer:
driver.findElement(By.id("submit")).click();
Alert alert = new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.alertIsPresent());
alert.accept();
60. Common Mistake: Treating HTML Modal as Alert
A CSS modal should not be handled with driver.switchTo().alert(). First inspect the popup and determine whether it is a DOM element or a native browser dialog.
61. Alert Test Case Example
| Test Case | Action | Expected Result |
| TC01 | Trigger simple alert | Alert appears |
| TC02 | Read alert text | Correct message is returned |
| TC03 | Accept alert | Alert closes |
| TC04 | Trigger confirm | Confirmation dialog appears |
| TC05 | Accept confirm | Positive action occurs |
| TC06 | Dismiss confirm | Action is cancelled |
| TC07 | Trigger prompt | Input dialog appears |
| TC08 | Enter prompt value | Value is accepted |
| TC09 | Dismiss prompt | Input operation is cancelled |
| TC10 | Validate message | Expected text matches actual text |
62. Complete Alert Test with TestNG
import java.time.Duration;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class AlertTest {
WebDriver driver;
WebDriverWait wait;
@BeforeMethod
public void setup() {
driver = new ChromeDriver();
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
driver.manage().window().maximize();
}
@Test
public void verifyAlert() {
driver.get("https://example.com");
driver.findElement(By.id("alertButton")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String message = alert.getText();
Assert.assertEquals(message, "Operation completed");
alert.accept();
}
@AfterMethod
public void tearDown() {
driver.quit();
}
}
63. Complete Confirmation Test
@Test
public void verifyConfirmation() {
driver.get("https://example.com");
driver.findElement(By.id("deleteButton")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String message = alert.getText();
Assert.assertEquals(message, "Are you sure you want to delete?");
alert.accept();
}
64. Complete Cancel Test
@Test
public void cancelDelete() {
driver.get("https://example.com");
driver.findElement(By.id("deleteButton")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.dismiss();
}
65. Complete Prompt Test
@Test
public void verifyPrompt() {
driver.get("https://example.com");
driver.findElement(By.id("promptButton")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String alertText = alert.getText();
System.out.println("Prompt: " + alertText);
alert.sendKeys("Selenium User");
alert.accept();
}
66. Alert Handling in a Data-Driven Test
Alert scenarios can also be tested using different input values. The test can trigger a prompt, provide test data, accept the prompt, and validate the result.
String[] names = {"John", "David", "Selenium"};
for (String name : names) {
driver.findElement(By.id("promptButton")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.sendKeys(name);
alert.accept();
System.out.println("Processed: " + name);
}
67. Alert Handling in Framework Architecture
Test Class
|
v
Page Object
|
v
Action triggers Alert
|
v
Alert Utility
|
+----> Wait for Alert
|
+----> Get Text
|
+----> Accept
|
+----> Dismiss
|
+----> Send Keys
|
v
Validation
|
v
Test Result
68. Alert Helper with Explicit Wait
public class AlertHelper {
private WebDriver driver;
private WebDriverWait wait;
public AlertHelper(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
public Alert getAlert() {
return wait.until(ExpectedConditions.alertIsPresent());
}
public String getAlertText() {
return getAlert().getText();
}
public void acceptAlert() {
getAlert().accept();
}
public void dismissAlert() {
getAlert().dismiss();
}
public void enterText(String text) {
getAlert().sendKeys(text);
}
}
69. Reusing the Alert Helper
AlertHelper alertHelper = new AlertHelper(driver);
driver.findElement(By.id("submit")).click();
String message = alertHelper.getAlertText();
System.out.println(message);
alertHelper.acceptAlert();
70. Alert Handling and Page Object Model
Page Object Model helps keep page-specific operations separate from test logic. Alert operations that are common across pages can be moved into an alert utility.
public class RegistrationPage {
private WebDriver driver;
private By registerButton = By.id("register");
public RegistrationPage(WebDriver driver) {
this.driver = driver;
}
public void clickRegister() {
driver.findElement(registerButton).click();
}
}
The test can then use the page object together with an alert helper.
71. Practical Project: Registration Alert
Consider a registration application that displays a JavaScript alert after successful registration.
RegistrationPage registrationPage = new RegistrationPage(driver);
registrationPage.clickRegister();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String message = alert.getText();
Assert.assertEquals(message, "Registration successful");
alert.accept();
72. Practical Project: Delete Confirmation
Consider an admin application where deleting a customer displays a confirmation dialog.
driver.findElement(By.id("deleteCustomer")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String message = alert.getText();
Assert.assertEquals(message, "Are you sure you want to delete this customer?");
alert.accept();
73. Practical Project: Cancel Delete
driver.findElement(By.id("deleteCustomer")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.dismiss();
String status = driver.findElement(By.id("customerStatus")).getText();
Assert.assertEquals(status, "Customer remains active");
74. Practical Project: Prompt-Based Username
driver.findElement(By.id("enterName")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.sendKeys("Automation Tester");
alert.accept();
String result = driver.findElement(By.id("displayName")).getText();
Assert.assertEquals(result, "Automation Tester");
75. Alert Handling Checklist
- Identify whether the popup is a native JavaScript dialog.
- Trigger the alert using the appropriate page action.
- Wait for the alert when necessary.
- Switch to the alert.
- Read the message if required.
- Accept or dismiss according to the test scenario.
- Use sendKeys() for prompt input.
- Validate important alert messages.
- Return to normal page interaction after closing the alert.
- Handle expected alert exceptions appropriately.
76. Alert Handling Best Practices for Automation Frameworks
- Create reusable alert helper methods.
- Prefer explicit synchronization over arbitrary sleeps.
- Keep alert validation close to the business scenario being tested.
- Use descriptive method names such as acceptAlert() and getAlertText().
- Keep test data separate from alert-handling implementation.
- Use assertions to validate critical alert messages.
- Do not use XPath to interact with native browser alerts.
- Distinguish JavaScript dialogs from HTML modals.
- Capture useful logs when alert handling fails.
- Keep the framework's wait strategy consistent.
77. Common Mistakes in Alert Handling
| Mistake | Problem | Better Approach |
| Using XPath on native alert | Native alert is not a DOM element | Use Alert interface |
| Switching immediately | Alert may not exist yet | Use alertIsPresent() |
| Using accept() for Cancel scenario | Wrong business path is tested | Use dismiss() |
| Not validating alert text | Message errors may go unnoticed | Use getText() and assertions |
| Using Thread.sleep() everywhere | Tests become slow and unreliable | Use condition-based waits |
| Confusing HTML modal with alert | Wrong Selenium API is used | Inspect the popup type |
78. Interview Question: What is an Alert in Selenium?
An alert is a browser-level JavaScript dialog that displays information, requests confirmation, or accepts user input. Selenium handles such dialogs using the Alert interface.
79. Interview Question: How Do You Switch to an Alert?
Alert alert = driver.switchTo().alert();
80. Interview Question: How Do You Accept an Alert?
driver.switchTo().alert().accept();
81. Interview Question: How Do You Dismiss an Alert?
driver.switchTo().alert().dismiss();
82. Interview Question: How Do You Get Alert Text?
String message = driver.switchTo().alert().getText();
83. Interview Question: How Do You Enter Text into a Prompt?
Alert alert = driver.switchTo().alert();
alert.sendKeys("Selenium");
alert.accept();
84. Interview Question: How Do You Wait for an Alert?
Alert alert = new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.alertIsPresent());
85. Interview Question: Can Selenium Handle JavaScript Alerts?
Yes. Selenium WebDriver provides the Alert interface for interacting with JavaScript alert, confirmation, and prompt dialogs.
86. Interview Question: Can XPath Locate a JavaScript Alert?
No. Native JavaScript alerts are not normal DOM elements. Selenium handles them using the Alert interface.
87. Interview Question: What is the Difference Between accept() and dismiss()?
accept() selects the OK or positive action. dismiss() selects the Cancel or negative action when available.
88. Interview Question: What is the Difference Between Alert and HTML Popup?
A native JavaScript alert is handled using Selenium's Alert interface, while an HTML popup is part of the DOM and can generally be handled using normal WebElement operations.
89. Interview Question: Which ExpectedCondition is Used for Alerts?
The commonly used condition is ExpectedConditions.alertIsPresent().
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
90. Interview Question: What Exception Occurs if an Alert is Not Present?
NoAlertPresentException can occur when Selenium attempts to access an alert when no alert is currently present.
91. Interview Question: Can a Prompt Accept User Input?
Yes. Selenium's Alert interface provides sendKeys() for entering text into a prompt.
92. Interview Question: Should Thread.sleep() Be Used for Alerts?
It can pause execution, but condition-based explicit waits are generally more suitable because they wait for the actual alert condition rather than using an arbitrary fixed delay.
93. Interview Question: How Do You Verify an Alert Message?
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String actual = alert.getText();
Assert.assertEquals(actual, "Expected message");
alert.accept();
94. Interview Question: What Happens if You Do Not Handle an Alert?
An active alert can block normal browser interaction. Subsequent WebDriver operations may fail until the alert is handled.
95. Alert Automation Strategy
Identify Popup
|
+----> Native JavaScript Alert?
| |
| +---- Yes ----> Alert Interface
| |
| +----> getText()
| +----> accept()
| +----> dismiss()
| +----> sendKeys()
|
+---- No ----> Check HTML Modal
|
v
WebElement
|
v
Normal Locators
96. Real-World Alert Scenarios
- Successful registration message.
- Invalid login warning.
- Delete confirmation.
- Logout confirmation.
- Session expiration notification.
- Unsaved changes warning.
- Form validation message.
- Data submission confirmation.
- Prompt-based user input.
- Administrative action confirmation.
97. Alert Testing Strategy for E-Commerce Applications
In an e-commerce application, alerts may appear during actions such as removing products, cancelling orders, submitting forms, or confirming account operations.
Login
|
v
Search Product
|
v
Add Product
|
v
Open Cart
|
v
Remove Product
|
v
Confirmation Alert
|
+----> Accept ----> Product Removed
|
+----> Dismiss ----> Product Remains
98. Alert Testing Strategy for Banking Applications
Banking applications may use confirmation dialogs for sensitive operations. Automated tests can verify the alert message and test both confirmation and cancellation paths where the application exposes native dialogs.
Initiate Transaction
|
v
Confirmation Dialog
|
+----> Accept
| |
| v
| Transaction Continues
|
+----> Dismiss
|
v
Transaction Cancelled
99. Alert Testing Strategy for Admin Applications
Administrative systems commonly require confirmation before deleting users, records, configurations, or other data.
Select Record
|
v
Click Delete
|
v
Confirm Alert
|
+----> Accept ----> Delete Record
|
+----> Dismiss ----> Keep Record
100. Alert Handling and Test Reliability
Reliable alert automation depends on identifying the correct popup type, synchronizing with its appearance, using the correct Alert API operation, and validating the expected outcome. A test should not assume that every popup will appear instantly or that every visual dialog is a JavaScript alert.
101. Alert Handling Quick Reference
| Requirement | Selenium Code |
| Switch to alert | driver.switchTo().alert() |
| Accept alert | alert.accept() |
| Dismiss alert | alert.dismiss() |
| Read message | alert.getText() |
| Enter prompt text | alert.sendKeys("text") |
| Wait for alert | ExpectedConditions.alertIsPresent() |
102. Mini Project: Complete Alert Automation
Build a small automation scenario that contains three buttons: Simple Alert, Confirm Alert, and Prompt Alert. The test suite should verify each type of dialog.
Simple Alert Test
driver.findElement(By.id("simpleAlert")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
Assert.assertEquals(alert.getText(), "Welcome to Selenium");
alert.accept();
Confirm Alert Test
driver.findElement(By.id("confirmAlert")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
Assert.assertEquals(alert.getText(), "Are you sure?");
alert.dismiss();
Prompt Alert Test
driver.findElement(By.id("promptAlert")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
Assert.assertEquals(alert.getText(), "Enter your name");
alert.sendKeys("Selenium Tester");
alert.accept();
103. Practical Learning Exercise
- Create a Selenium Maven project.
- Add Selenium WebDriver dependencies.
- Launch Chrome.
- Open an application containing JavaScript dialogs.
- Trigger a simple alert.
- Read the alert message.
- Accept the alert.
- Trigger a confirmation dialog.
- Test both accept and dismiss scenarios.
- Trigger a prompt dialog.
- Enter text using sendKeys().
- Accept the prompt.
- Validate the resulting page state.
- Add explicit waits.
- Convert repeated alert operations into a reusable helper.
104. Final Alert Handling Example
import java.time.Duration;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class AlertsDemo {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
try {
driver.manage().window().maximize();
driver.get("https://example.com");
driver.findElement(By.id("alertButton")).click();
Alert alert =
wait.until(ExpectedConditions.alertIsPresent());
String message = alert.getText();
System.out.println("Alert Message: " + message);
alert.accept();
} finally {
driver.quit();
}
}
}
105. Summary
Alerts are browser-level JavaScript dialogs that require special handling in Selenium WebDriver. Selenium provides the Alert interface to interact with simple alerts, confirmation dialogs, and prompt dialogs.
The most important methods are accept(), dismiss(), getText(), and sendKeys(). For dynamic alerts, ExpectedConditions.alertIsPresent() with WebDriverWait provides condition-based synchronization.
It is also important to distinguish native JavaScript alerts from HTML/CSS modals. Native alerts use the Alert API, while HTML modals are normal DOM elements and should be handled using WebElement methods and appropriate locators.
For professional Selenium automation frameworks, alert handling should be synchronized, reusable, validated, and integrated cleanly with Page Object Model and utility classes.
106. Quick Revision
- Alert interface: Used for native JavaScript dialogs.
- switchTo().alert(): Switches WebDriver focus to the active alert.
- accept(): Clicks OK/positive action.
- dismiss(): Clicks Cancel/negative action.
- getText(): Reads alert message.
- sendKeys(): Enters text into a prompt.
- alertIsPresent(): Waits for an alert to appear.
- NoAlertPresentException: Occurs when an alert is not available.
- HTML modal: Handle using normal WebElement methods.
- Best practice: Prefer explicit synchronization over arbitrary fixed delays.
107. Selenium Course Resource
Learn Selenium WebDriver, Java automation, TestNG, Page Object Model, browser interactions, alerts, frames, windows, waits, dynamic elements, and automation framework concepts through the JustAcademy Selenium Training Course.
For course demonstration and registration, visit the JustAcademy Selenium Course Demo Registration page.