Confirmation Alerts in Selenium WebDriver
A Confirmation Alert is a native JavaScript dialog used by a web application to ask the user whether an action should be confirmed or cancelled. Unlike a simple JavaScript alert, a confirmation alert normally provides two choices: OK and Cancel.
In Selenium WebDriver, confirmation alerts are handled using Selenium's Alert interface rather than normal WebElement locators. Selenium provides methods to read the alert text, accept the confirmation, or dismiss it. :contentReference[oaicite:0]{index=0}
Confirmation alerts are commonly used for operations such as deleting records, cancelling orders, logging out, removing users, deactivating accounts, submitting important forms, or performing other actions that require explicit confirmation.
For complete Selenium WebDriver training and practical automation learning, visit Selenium Training and Register for Course Demo.
1. What is a Confirmation Alert?
A confirmation alert is a browser-controlled JavaScript dialog generally created using the confirm() function. It displays a message and allows the user to either accept or cancel an operation.
confirm("Are you sure you want to delete this record?");
A typical confirmation dialog contains:
- A confirmation message.
- An OK button.
- A Cancel button.
Selenium documentation describes a confirm box as similar to a normal alert, except that the user can also choose to cancel the message. :contentReference[oaicite:1]{index=1}
2. Why are Confirmation Alerts Used?
Confirmation alerts are commonly used to prevent users from accidentally performing important or destructive operations.
For example, when a user clicks a Delete button, the application may display:
Are you sure you want to delete this user?
OK Cancel
The user must make a decision before the operation continues.
Common Uses
- Deleting a user.
- Deleting a product.
- Cancelling an order.
- Logging out of an application.
- Deactivating an account.
- Removing a record.
- Submitting an important transaction.
- Resetting application data.
3. JavaScript confirm() Function
A confirmation dialog can be created using JavaScript's confirm() function.
function deleteUser() {
let result = confirm("Are you sure you want to delete this user?");
if (result) {
console.log("User deleted");
} else {
console.log("Delete cancelled");
}
}
The result of the confirmation determines which branch of the application logic should execute.
confirm()
|
"Are you sure?"
/ \
OK Cancel
| |
Confirm Cancel
Action Action
4. Simple Confirmation Alert Example
<button onclick="confirmDelete()">Delete User</button>
<script>
function confirmDelete() {
if (confirm("Are you sure you want to delete this user?")) {
alert("User deleted successfully");
}
}
</script>
When the Delete button is clicked, the browser displays the confirmation dialog. Selenium can automate both the OK and Cancel scenarios.
5. Types of JavaScript Dialogs
| Dialog Type | JavaScript Function | Buttons | Text Input |
| Alert | alert() | OK | No |
| Confirmation | confirm() | OK / Cancel | No |
| Prompt | prompt() | OK / Cancel | Yes |
Selenium WebDriver provides an API for interacting with these native JavaScript popup types. :contentReference[oaicite:2]{index=2}
6. Confirmation Alert vs Simple Alert
| Feature | Simple Alert | Confirmation Alert |
| JavaScript Function | alert() | confirm() |
| Purpose | Display information. | Ask the user to confirm or cancel. |
| OK | Yes | Yes |
| Cancel | No separate Cancel choice. | Yes |
| Selenium Accept | accept() | accept() |
| Selenium Dismiss | Dismisses the alert. | Usually selects Cancel. |
7. Confirmation Alert vs Prompt
| Feature | Confirmation Alert | Prompt |
| Function | confirm() | prompt() |
| OK | Yes | Yes |
| Cancel | Yes | Yes |
| Text Input | No | Yes |
| Accept | accept() | accept() |
| Cancel | dismiss() | dismiss() |
| Input Method | Not normally required | sendKeys() |
8. Selenium Alert Interface
Selenium provides the Alert interface for interacting with native browser dialogs.
Alert alert = driver.switchTo().alert();
The main operations available for alert handling include accepting, dismissing, retrieving text, and sending input where supported. :contentReference[oaicite:3]{index=3}
| Method | Purpose |
accept() | Accepts the currently displayed alert. |
dismiss() | Dismisses the currently displayed alert. |
getText() | Retrieves the text displayed by the alert in Selenium Java. |
sendKeys() | Enters text into a prompt dialog. |
9. Switching to a Confirmation Alert
Before interacting with a native confirmation alert, Selenium needs to switch to the active alert.
Alert alert = driver.switchTo().alert();
The basic workflow is:
Click Button
↓
Confirmation Alert Appears
↓
driver.switchTo().alert()
↓
Alert Object
↓
getText()
↓
accept() / dismiss()
Selenium's official Java examples use driver.switchTo().alert() to obtain the alert before interacting with it. :contentReference[oaicite:4]{index=4}
10. Accepting a Confirmation Alert
The accept() method is used when the test should select the OK option.
Alert alert = driver.switchTo().alert();
alert.accept();
For a confirmation dialog, accepting normally corresponds to choosing OK. Selenium's alert API defines accept() as accepting the available alert dialog. :contentReference[oaicite:5]{index=5}
11. Dismissing a Confirmation Alert
The dismiss() method is used when the test should select the Cancel option.
Alert alert = driver.switchTo().alert();
alert.dismiss();
For confirm() and prompt() dialogs, dismissing corresponds to choosing Cancel. :contentReference[oaicite:6]{index=6}
12. Reading Confirmation Alert Text
The confirmation message can be read using getText() in Selenium Java.
Alert alert = driver.switchTo().alert();
String message = alert.getText();
System.out.println("Alert Message: " + message);
Reading the message is useful when the test needs to confirm that the correct warning or confirmation text is displayed.
13. Verifying Confirmation Alert Text
A good automation test should validate the confirmation message before performing the confirmation action.
Alert alert = driver.switchTo().alert();
String actualMessage = alert.getText();
String expectedMessage =
"Are you sure you want to delete this user?";
Assert.assertEquals(actualMessage, expectedMessage);
alert.accept();
This test verifies both the message and the user's confirmation action.
14. Complete Confirmation Alert Flow
Open Application
↓
Perform Action
↓
Confirmation Alert
↓
Wait for Alert
↓
Switch to Alert
↓
Read Alert Text
↓
Validate Text
↓
┌──────────────┐
↓ ↓
accept() dismiss()
↓ ↓
OK Cancel
↓ ↓
Confirm Cancel
Action Action
↓ ↓
Verify Verify
Result Result
15. Basic Selenium Confirmation Alert Example
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ConfirmationAlertTest {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
driver.findElement(By.id("deleteButton")).click();
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
driver.quit();
}
}
16. Confirmation Alert with Text Validation
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
public class ConfirmationAlertValidation {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
driver.findElement(By.id("deleteButton")).click();
Alert alert = driver.switchTo().alert();
String actualText = alert.getText();
String expectedText =
"Are you sure you want to delete this user?";
Assert.assertEquals(actualText, expectedText);
alert.accept();
driver.quit();
}
}
17. Testing the OK Scenario
The OK scenario verifies what happens when the user confirms the operation.
driver.findElement(By.id("deleteButton")).click();
Alert alert = driver.switchTo().alert();
Assert.assertEquals(
alert.getText(),
"Are you sure you want to delete this user?"
);
alert.accept();
After accepting the alert, the test should verify the expected application result.
18. Testing the Cancel Scenario
The Cancel scenario verifies that the operation is not performed when the user rejects the confirmation.
driver.findElement(By.id("deleteButton")).click();
Alert alert = driver.switchTo().alert();
Assert.assertEquals(
alert.getText(),
"Are you sure you want to delete this user?"
);
alert.dismiss();
After dismissal, the test should verify that the original data or application state remains unchanged.
19. Confirmation Alert with Explicit Wait
Confirmation alerts may not appear immediately after clicking a button. Selenium provides the alertIsPresent() expected condition for waiting until an alert becomes available.
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
alert.accept();
Selenium's current documentation demonstrates waiting with ExpectedConditions.alertIsPresent() before switching to and interacting with the alert. :contentReference[oaicite:7]{index=7}
20. Complete Example with Explicit Wait
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 ConfirmationAlertWaitTest {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
driver.get("https://example.com");
driver.findElement(By.id("deleteButton")).click();
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
String message = alert.getText();
System.out.println(
"Confirmation Message: " + message
);
alert.accept();
driver.quit();
}
}
21. Why Explicit Wait is Important
Suppose the application needs some time to execute JavaScript before showing the confirmation alert. If Selenium immediately calls switchTo().alert(), the alert may not yet be available.
Click Delete
↓
JavaScript Processing
↓
Alert Appears
↓
Selenium Detects Alert
↓
Interact with Alert
Using alertIsPresent() allows Selenium to wait for the required condition instead of relying on an arbitrary fixed delay.
22. Using Thread.sleep()
A beginner may use Thread.sleep() to wait for a confirmation alert.
driver.findElement(By.id("deleteButton")).click();
Thread.sleep(3000);
Alert alert = driver.switchTo().alert();
alert.accept();
Although a fixed delay may work in some situations, explicit waits are generally more appropriate when the goal is to wait for a specific condition.
23. Recommended Synchronization
driver.findElement(By.id("deleteButton")).click();
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
alert.accept();
24. NoAlertPresentException
If Selenium attempts to access an alert when no alert is currently displayed, an alert-related exception can occur.
Alert alert = driver.switchTo().alert();
If no alert is available, Selenium can report that no alert is present. The WebDriver alert commands also define this condition as a possible error when no alert is displayed. :contentReference[oaicite:8]{index=8}
try {
Alert alert = driver.switchTo().alert();
alert.accept();
} catch (NoAlertPresentException e) {
System.out.println(
"Confirmation alert was not present."
);
}
25. Handling an Optional Confirmation Alert
Some application workflows may display a confirmation dialog only under certain conditions. If the alert is optional, the test can handle the possibility that it does not appear.
try {
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(5));
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
alert.dismiss();
} catch (TimeoutException e) {
System.out.println(
"No confirmation alert appeared."
);
}
For a mandatory alert, however, silently continuing may hide an application defect. The expected behavior should be reflected in the test assertions and reporting.
26. Confirmation Alert After Delete
Delete operations are one of the most common examples of confirmation dialogs.
driver.findElement(By.id("deleteUser")).click();
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertEquals(
alert.getText(),
"Are you sure you want to delete this user?"
);
alert.accept();
27. Confirmation Alert After Logout
driver.findElement(By.id("logout")).click();
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertEquals(
alert.getText(),
"Are you sure you want to logout?"
);
alert.accept();
After accepting, the test can verify that the application navigated to the login page or otherwise reflects the expected logged-out state.
28. Confirmation Alert for Order Cancellation
driver.findElement(By.id("cancelOrder")).click();
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertTrue(
alert.getText().contains(
"cancel this order"
)
);
alert.accept();
29. Canceling an Order Through the Alert
driver.findElement(By.id("cancelOrder")).click();
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
alert.dismiss();
System.out.println(
"Order cancellation was cancelled."
);
30. Confirmation Alert After Form Submission
Important forms can display a confirmation alert before the submission is finalized.
driver.findElement(By.id("submitForm")).click();
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertTrue(
alert.getText().contains(
"submit this form"
)
);
alert.accept();
31. Confirmation Alert for Account Deactivation
driver.findElement(By.id("deactivateAccount")).click();
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
String message = alert.getText();
Assert.assertTrue(
message.contains("deactivate")
);
alert.dismiss();
32. Confirmation Alert vs HTML Modal
A native JavaScript confirmation alert should not be confused with an HTML/CSS modal dialog.
| Native Confirmation Alert | HTML Modal |
Created by JavaScript such as confirm(). | Created using HTML, CSS and JavaScript. |
Handled using Alert. | Handled using WebElement. |
Use switchTo().alert(). | Use normal locators. |
Use accept() or dismiss(). | Click the modal's HTML buttons. |
Native Confirmation
Alert alert = driver.switchTo().alert();
alert.accept();
HTML Modal
WebElement modal =
driver.findElement(By.id("confirmationModal"));
WebElement confirmButton =
modal.findElement(By.id("confirmButton"));
confirmButton.click();
33. Common Mistake: Treating Alert as WebElement
A native confirmation alert is not normally handled by locating an HTML element with XPath or CSS.
// Incorrect for a native JavaScript confirmation
driver.findElement(
By.xpath("//div[@class='alert']")
).click();
Correct approach:
Alert alert = driver.switchTo().alert();
alert.accept();
34. Common Mistake: Using driver.accept()
The accept() operation belongs to the Alert object.
// Incorrect
driver.accept();
Correct:
Alert alert = driver.switchTo().alert();
alert.accept();
35. Common Mistake: Using getText() on WebDriver
// Incorrect
String text = driver.getText();
Correct:
Alert alert = driver.switchTo().alert();
String text = alert.getText();
36. Validating Dynamic Confirmation Messages
Sometimes the alert message contains dynamic information, such as a username, product name, order number, or employee name.
Alert alert = driver.switchTo().alert();
String message = alert.getText();
Assert.assertTrue(
message.contains("Are you sure you want to delete")
);
alert.accept();
Using contains() can be useful when only part of the message is stable.
37. Dynamic User Confirmation Example
String userName = "Rahul";
driver.findElement(By.id("deleteUser")).click();
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
String message = alert.getText();
Assert.assertTrue(
message.contains(userName)
);
alert.accept();
38. Confirmation Alert in 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.Test;
public class ConfirmationAlertTest {
@Test
public void verifyDeleteConfirmation() {
WebDriver driver = new ChromeDriver();
try {
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
driver.get("https://example.com");
driver.findElement(
By.id("deleteButton")
).click();
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertEquals(
alert.getText(),
"Are you sure you want to delete this user?"
);
alert.accept();
} finally {
driver.quit();
}
}
}
39. TestNG Test for Cancel Operation
@Test
public void verifyDeleteCancel() {
WebDriver driver = new ChromeDriver();
try {
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
driver.get("https://example.com");
driver.findElement(
By.id("deleteButton")
).click();
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertTrue(
alert.getText().contains(
"Are you sure"
)
);
alert.dismiss();
Assert.assertTrue(
driver.findElement(
By.id("userRecord")
).isDisplayed()
);
} finally {
driver.quit();
}
}
40. Confirmation Alert Utility Method
In a large automation framework, common alert operations can be placed into reusable utility methods.
public void acceptConfirmationAlert(WebDriver driver) {
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
alert.accept();
}
41. Reusable Dismiss Alert Method
public void dismissConfirmationAlert(WebDriver driver) {
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
alert.dismiss();
}
42. Reusable Alert Text Method
public String getConfirmationAlertText(WebDriver driver) {
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
return alert.getText();
}
43. Using Alert Utility
driver.findElement(
By.id("deleteButton")
).click();
String message =
getConfirmationAlertText(driver);
Assert.assertTrue(
message.contains("Are you sure")
);
acceptConfirmationAlert(driver);
44. Confirmation Alerts with Page Object Model
In the Page Object Model, the page object can expose the action that triggers the confirmation dialog, while alert handling can remain in a utility or test layer.
public class UserPage {
private WebDriver driver;
private By deleteButton =
By.id("deleteButton");
public UserPage(WebDriver driver) {
this.driver = driver;
}
public void clickDelete() {
driver.findElement(
deleteButton
).click();
}
}
Test class:
UserPage userPage =
new UserPage(driver);
userPage.clickDelete();
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertEquals(
alert.getText(),
"Are you sure you want to delete this user?"
);
alert.accept();
45. Real-World Example: Delete Employee
Consider an employee management application.
Employee Dashboard
↓
Search Employee
↓
Select Employee
↓
Click Delete
↓
Confirmation Alert
↓
"Are you sure you want to delete this employee?"
↓
┌─────────────┐
↓ ↓
OK Cancel
↓ ↓
Delete Keep
Employee Employee
The automation should test both branches.
46. Employee Delete - Accept Test
driver.findElement(
By.id("deleteEmployee")
).click();
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertEquals(
alert.getText(),
"Are you sure you want to delete this employee?"
);
alert.accept();
Assert.assertTrue(
driver.findElement(
By.id("successMessage")
).isDisplayed()
);
47. Employee Delete - Cancel Test
driver.findElement(
By.id("deleteEmployee")
).click();
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
alert.dismiss();
Assert.assertTrue(
driver.findElement(
By.id("employeeRecord")
).isDisplayed()
);
48. Confirmation Alert Decision Table
| Scenario | User Action | Selenium Method | Expected Result |
| Confirm deletion | OK | accept() | Record is deleted. |
| Cancel deletion | Cancel | dismiss() | Record remains. |
| Confirm logout | OK | accept() | User is logged out. |
| Cancel logout | Cancel | dismiss() | User remains logged in. |
| Confirm order cancellation | OK | accept() | Order is cancelled. |
| Reject order cancellation | Cancel | dismiss() | Order remains active. |
49. Confirmation Alert and Multiple Dialogs
An application can potentially produce dialogs sequentially. Each displayed dialog should be handled before the next interaction.
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert1 = wait.until(
ExpectedConditions.alertIsPresent()
);
System.out.println(
alert1.getText()
);
alert1.accept();
Alert alert2 = wait.until(
ExpectedConditions.alertIsPresent()
);
System.out.println(
alert2.getText()
);
alert2.dismiss();
50. Confirmation Alert Inside an IFrame
A page can trigger a native JavaScript alert from code associated with an iframe. Selenium's examples demonstrate switching to the frame, triggering the alert, waiting for it, and then using the Alert API. :contentReference[oaicite:9]{index=9}
WebElement iframe =
driver.findElement(
By.name("iframeWithAlert")
);
driver.switchTo().frame(iframe);
driver.findElement(
By.id("alertInFrame")
).click();
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
System.out.println(
alert.getText()
);
alert.accept();
driver.switchTo().defaultContent();
51. Confirmation Alert vs Browser Window
A confirmation alert is different from a new browser window or tab.
| Situation | Selenium Approach |
| JavaScript confirmation | driver.switchTo().alert() |
| New browser window/tab | driver.switchTo().window() |
| HTML modal | driver.findElement() |
| Iframe | driver.switchTo().frame() |
52. Confirmation Alert and unhandledPromptBehavior
WebDriver also provides the unhandledPromptBehavior capability, which defines how an unhandled user prompt should be treated. Selenium documents behaviors such as accept, dismiss, accept and notify, dismiss and notify, and ignore. :contentReference[oaicite:10]{index=10}
For an expected confirmation dialog, explicitly handling the alert in the test is often clearer because the test shows exactly which user action is being verified.
53. Confirmation Alert and Test Synchronization
Click Action
↓
Application Processing
↓
JavaScript confirm()
↓
Alert Becomes Available
↓
alertIsPresent()
↓
switchTo().alert()
↓
getText()
↓
accept() / dismiss()
↓
Verify Application State
54. Confirmation Alert and Application State
Handling the alert is only one part of the test. After clicking OK or Cancel, the test should verify the resulting application state.
After Accept
Delete Button
↓
Confirmation Alert
↓
accept()
↓
Record Deleted
↓
Verify Record Removed
After Dismiss
Delete Button
↓
Confirmation Alert
↓
dismiss()
↓
Delete Cancelled
↓
Verify Record Still Exists
55. Confirmation Alert and Dynamic Applications
Modern applications may execute JavaScript or asynchronous processing before displaying a confirmation dialog. Because the timing can vary, alert synchronization should be based on the alert's actual availability.
driver.findElement(
By.id("processButton")
).click();
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(15)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
String message = alert.getText();
Assert.assertTrue(
message.contains("confirmation")
);
alert.accept();
56. Why Confirmation Alert Tests Can Fail
- The test tries to access the alert before it appears.
- The application does not trigger the alert.
- The confirmation message has changed.
- The popup is actually an HTML modal instead of a native JavaScript alert.
- The test uses an inappropriate fixed wait.
- The test does not verify the expected application state.
- The wrong action is performed after the alert appears.
57. How to Make Confirmation Alert Tests Stable
- Use
WebDriverWait for dynamically appearing alerts.
- Use
ExpectedConditions.alertIsPresent().
- Validate the alert text.
- Test both OK and Cancel paths.
- Verify the application state after the alert action.
- Use reusable alert utilities in large frameworks.
- Distinguish native alerts from HTML modals.
- Avoid unnecessary hard-coded delays.
58. Confirmation Alert Logging
Logging the alert text can make debugging easier.
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
String message = alert.getText();
System.out.println(
"Confirmation Alert: " + message
);
alert.accept();
59. Confirmation Alert Regression Scenarios
Whenever a business workflow containing a confirmation dialog changes, regression tests should verify the important branches of that workflow.
- Confirmation dialog appears.
- Correct confirmation message is displayed.
- OK confirms the operation.
- Cancel prevents the operation.
- Application state is correct after OK.
- Application state is correct after Cancel.
- Unexpected missing alerts are reported.
60. Confirmation Alert Test Scenarios
| Test Scenario | Validation |
| Alert appears | Use alertIsPresent(). |
| Correct message | Use getText(). |
| User confirms | Use accept(). |
| User cancels | Use dismiss(). |
| Alert missing | Report the expected behavior failure. |
| Wrong message | Fail message validation. |
| Action succeeds | Verify resulting application state. |
| Action cancelled | Verify original state remains. |
61. Confirmation Alert Exception Reporting
try {
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertTrue(
alert.getText().contains(
"Are you sure"
)
);
alert.accept();
} catch (TimeoutException e) {
Assert.fail(
"Expected confirmation alert did not appear."
);
}
62. Mini Project: Employee Management Confirmation Alert
Create automated tests for an employee management application where deleting an employee requires confirmation.
Application Flow
Login
↓
Employee Dashboard
↓
Search Employee
↓
Click Delete
↓
Confirmation Alert
↓
Verify Message
↓
Test OK
↓
Verify Employee Deleted
Second Scenario:
Click Delete
↓
Confirmation Alert
↓
Test Cancel
↓
Verify Employee Still Exists
63. Mini Project Test Cases
| Test Case | Expected Result |
| Verify alert appears | Confirmation alert is displayed. |
| Verify alert message | Expected confirmation text is displayed. |
| Accept deletion | Employee is deleted. |
| Cancel deletion | Employee remains available. |
| Verify synchronization | Test waits for the alert. |
| Verify unexpected alert absence | Test reports the problem. |
64. Complete Mini Project 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;
import org.testng.Assert;
import org.testng.annotations.Test;
public class EmployeeDeleteTest {
@Test
public void verifyEmployeeDeletion() {
WebDriver driver = new ChromeDriver();
try {
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
driver.get(
"https://example.com/employees"
);
driver.findElement(
By.id("deleteEmployee")
).click();
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
String actualMessage =
alert.getText();
Assert.assertEquals(
actualMessage,
"Are you sure you want to delete this employee?"
);
alert.accept();
Assert.assertTrue(
driver.findElement(
By.id("successMessage")
).isDisplayed()
);
} finally {
driver.quit();
}
}
}
65. Confirmation Alert Framework Design
Automation Framework
|
+-- Page Objects
|
+-- Test Classes
|
+-- Alert Utility
| |
| +-- waitForAlert()
| +-- getAlertText()
| +-- acceptAlert()
| +-- dismissAlert()
|
+-- Wait Utility
|
+-- Assertions
|
+-- Reporting
66. Alert Utility Class
public class AlertUtility {
public static Alert waitForAlert(
WebDriver driver,
int seconds) {
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(seconds)
);
return wait.until(
ExpectedConditions.alertIsPresent()
);
}
public static String getText(
WebDriver driver,
int seconds) {
Alert alert =
waitForAlert(driver, seconds);
return alert.getText();
}
public static void accept(
WebDriver driver,
int seconds) {
Alert alert =
waitForAlert(driver, seconds);
alert.accept();
}
public static void dismiss(
WebDriver driver,
int seconds) {
Alert alert =
waitForAlert(driver, seconds);
alert.dismiss();
}
}
67. Using Alert Utility Class
driver.findElement(
By.id("deleteButton")
).click();
String message =
AlertUtility.getText(driver, 10);
Assert.assertTrue(
message.contains("Are you sure")
);
AlertUtility.accept(driver, 10);
68. Best Practices for Confirmation Alerts
- Use the
Alert interface for native JavaScript confirmation dialogs.
- Use
switchTo().alert() to access the active alert.
- Use
getText() to validate the displayed message.
- Use
accept() for the OK/confirm scenario.
- Use
dismiss() for the Cancel scenario.
- Use
alertIsPresent() when alert timing is dynamic.
- Test both confirmation and cancellation paths.
- Verify the application state after handling the alert.
- Do not use XPath or CSS locators for a native JavaScript alert.
- Use reusable utility methods in larger automation frameworks.
- Do not silently ignore a missing alert when the alert is mandatory for the workflow.
69. Common Mistakes
| Mistake | Correct Approach |
| Using XPath for a native confirmation alert | Use switchTo().alert(). |
Calling driver.accept() | Switch to Alert and call accept(). |
Calling driver.getText() | Use alert.getText(). |
Always using Thread.sleep() | Prefer explicit waits. |
| Testing only OK | Test both accept() and dismiss(). |
| Not validating alert text | Use getText() and assertions. |
| Using Alert API for an HTML modal | Use WebElement locators for the HTML modal. |
| Not verifying final state | Assert the result after handling the alert. |
70. Confirmation Alert Checklist
- Identify whether the popup is a native JavaScript confirmation.
- Identify the action that triggers the alert.
- Click or perform the triggering action.
- Wait for the alert when required.
- Switch to the alert.
- Read the confirmation message.
- Validate the expected message.
- Test the OK scenario using
accept().
- Test the Cancel scenario using
dismiss().
- Verify the application state after each action.
- Handle exceptions appropriately.
- Use reusable alert utilities when appropriate.
71. Interview Question: What is a Confirmation Alert?
A confirmation alert is a native JavaScript dialog generally created using confirm(). It asks the user whether an operation should proceed and normally provides OK and Cancel choices.
72. Interview Question: How do you handle a Confirmation Alert in Selenium?
Alert alert = driver.switchTo().alert();
alert.accept();
For Cancel:
Alert alert = driver.switchTo().alert();
alert.dismiss();
73. Interview Question: What is the Difference Between accept() and dismiss()?
| Method | Purpose |
accept() | Accepts the alert; for a confirmation dialog this normally selects OK. |
dismiss() | Dismisses the alert; for a confirmation dialog this normally selects Cancel. |
74. Interview Question: How do you Get the Text of a Confirmation Alert?
Alert alert = driver.switchTo().alert();
String text = alert.getText();
75. Interview Question: Can XPath be Used for a Native Confirmation Alert?
No. A native JavaScript confirmation dialog is handled through Selenium's Alert API rather than normal DOM locators.
76. Interview Question: How do you Wait for a Confirmation Alert?
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
77. Interview Question: What Exception Can Occur if No Alert is Present?
When Selenium attempts to interact with an alert that is not available, an alert-related no-alert condition can occur. In Java Selenium automation, this is commonly handled using NoAlertPresentException.
78. Interview Question: What is alertIsPresent()?
alertIsPresent() is an expected condition used with an explicit wait to wait until a browser alert is available.
79. Interview Question: What is the Difference Between a JavaScript Confirmation and an HTML Modal?
A JavaScript confirmation is handled using Selenium's Alert API, while an HTML modal is part of the page DOM and is generally handled using WebElement locators.
80. Interview Question: Why Should Both OK and Cancel be Tested?
Because the application can execute different business logic depending on the user's choice. Testing both paths verifies both confirmation and cancellation behavior.
81. Interview Question: Can Confirmation Alert Text be Validated?
Yes. Selenium provides alert text retrieval through the Alert API, allowing the test to verify that the expected confirmation message is displayed. :contentReference[oaicite:11]{index=11}
82. Interview Question: Can sendKeys() be Used with a Confirmation Alert?
sendKeys() is primarily used with a prompt dialog because a prompt provides a text-input area. A normal confirmation dialog does not require text input.
83. Interview Question: Why Use WebDriverWait Instead of Thread.sleep()?
WebDriverWait waits for a specific condition such as an alert becoming present, whereas Thread.sleep() pauses for a fixed amount of time regardless of whether the alert is ready.
84. Quick Revision Table
| Requirement | Selenium Code |
| Switch to alert | driver.switchTo().alert() |
| Read alert text | alert.getText() |
| Click OK | alert.accept() |
| Click Cancel | alert.dismiss() |
| Wait for alert | ExpectedConditions.alertIsPresent() |
| Handle no alert | NoAlertPresentException |
| Wait dynamically | WebDriverWait |
85. Confirmation Alert Cheat Sheet
// Trigger confirmation
driver.findElement(
By.id("deleteButton")
).click();
// Wait for confirmation
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
// Read message
String message = alert.getText();
// Validate message
Assert.assertEquals(
message,
"Are you sure you want to delete this user?"
);
// Confirm
alert.accept();
// Or cancel
// alert.dismiss();
86. Recommended Learning Sequence
- Understand JavaScript
confirm().
- Understand the difference between alert, confirm, and prompt.
- Learn the Selenium
Alert interface.
- Learn
switchTo().alert().
- Learn
getText().
- Learn
accept().
- Learn
dismiss().
- Learn explicit waits.
- Learn
alertIsPresent().
- Automate OK scenarios.
- Automate Cancel scenarios.
- Add assertions.
- Create reusable alert utilities.
- Integrate alert handling into a Selenium framework.
87. Common Errors and Solutions
| Error/Problem | Possible Cause | Solution |
NoAlertPresentException | Alert is not available. | Wait for the alert and verify the triggering action. |
| Unable to locate alert with XPath | Native alert is not handled as a normal DOM element. | Use switchTo().alert(). |
| Random test failures | Synchronization problem. | Use alertIsPresent(). |
| Cancel path not tested | Only OK scenario was automated. | Add a dismiss() scenario. |
| Wrong alert message | Expected text does not match actual text. | Validate and update the test according to the application's expected behavior. |
| Alert API does not work | Popup may be an HTML modal. | Inspect the popup and use WebElement locators if it is DOM-based. |
88. Final Summary
Confirmation Alerts are native JavaScript dialogs that ask users to confirm or cancel an operation. They are commonly created using JavaScript's confirm() function and normally provide OK and Cancel choices.
In Selenium WebDriver, confirmation alerts are handled using the Alert interface. The standard workflow is to trigger the alert, wait for it when necessary, switch to it, read and validate the message, and then select either accept() or dismiss(). Selenium's official documentation demonstrates this same approach for confirmation dialogs. :contentReference[oaicite:12]{index=12}
Trigger Action
↓
Confirmation Alert
↓
Wait for Alert
↓
switchTo().alert()
↓
getText()
↓
Validate Message
↓
┌───────────────┐
↓ ↓
accept() dismiss()
↓ ↓
OK Cancel
↓ ↓
Confirm Reject
Action Action
↓ ↓
Verify Verify
Success No Change
The most important Selenium methods to remember are:
driver.switchTo().alert() – accesses the active native alert.
alert.getText() – retrieves the confirmation message.
alert.accept() – accepts the confirmation.
alert.dismiss() – dismisses the confirmation.
ExpectedConditions.alertIsPresent() – waits for an alert to become available.
89. Selenium Training Resources
For detailed Selenium WebDriver training covering locators, waits, alerts, TestNG, Page Object Model, automation frameworks, and practical testing, visit Selenium Training.
To explore the course through a demo session, visit Register for Course Demo.