Popular Searches
Popular Course Categories
Popular Courses

Confirmation Alerts

Handling Browser Components

<div class="selenium-notes">

<h1>Confirmation Alerts in Selenium WebDriver</h1>

<p>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: <strong>OK</strong> and <strong>Cancel</strong>.</p>

<p>In Selenium WebDriver, confirmation alerts are handled using Selenium's <strong>Alert</strong> 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}</p>

<p>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.</p>

<p>For complete Selenium WebDriver training and practical automation learning, visit <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training</a> and <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a>.</p>

<hr>

<h2>1. What is a Confirmation Alert?</h2>

<p>A confirmation alert is a browser-controlled JavaScript dialog generally created using the <code>confirm()</code> function. It displays a message and allows the user to either accept or cancel an operation.</p>

<pre><code>confirm("Are you sure you want to delete this record?");</code></pre>

<p>A typical confirmation dialog contains:</p>

<ul>

<li>A confirmation message.</li>

<li>An <strong>OK</strong> button.</li>

<li>A <strong>Cancel</strong> button.</li>

</ul>

<p>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}</p>

<hr>

<h2>2. Why are Confirmation Alerts Used?</h2>

<p>Confirmation alerts are commonly used to prevent users from accidentally performing important or destructive operations.</p>

<p>For example, when a user clicks a Delete button, the application may display:</p>

<pre><code>Are you sure you want to delete this user?

 

        OK        Cancel</code></pre>

<p>The user must make a decision before the operation continues.</p>

<h3>Common Uses</h3>

<ul>

<li>Deleting a user.</li>

<li>Deleting a product.</li>

<li>Cancelling an order.</li>

<li>Logging out of an application.</li>

<li>Deactivating an account.</li>

<li>Removing a record.</li>

<li>Submitting an important transaction.</li>

<li>Resetting application data.</li>

</ul>

<hr>

<h2>3. JavaScript confirm() Function</h2>

<p>A confirmation dialog can be created using JavaScript's <code>confirm()</code> function.</p>

<pre><code>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");

    }

}</code></pre>

<p>The result of the confirmation determines which branch of the application logic should execute.</p>

<pre><code>                confirm()

                    |

          "Are you sure?"

             /        \

           OK        Cancel

           |            |

        Confirm       Cancel

        Action        Action</code></pre>

<hr>

<h2>4. Simple Confirmation Alert Example</h2>

<pre><code>&lt;button onclick="confirmDelete()"&gt;Delete User&lt;/button&gt;

 

&lt;script&gt;

function confirmDelete() {

    if (confirm("Are you sure you want to delete this user?")) {

        alert("User deleted successfully");

    }

}

&lt;/script&gt;</code></pre>

<p>When the Delete button is clicked, the browser displays the confirmation dialog. Selenium can automate both the OK and Cancel scenarios.</p>

<hr>

<h2>5. Types of JavaScript Dialogs</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Dialog Type</th><th>JavaScript Function</th><th>Buttons</th><th>Text Input</th></tr>

<tr><td>Alert</td><td><code>alert()</code></td><td>OK</td><td>No</td></tr>

<tr><td>Confirmation</td><td><code>confirm()</code></td><td>OK / Cancel</td><td>No</td></tr>

<tr><td>Prompt</td><td><code>prompt()</code></td><td>OK / Cancel</td><td>Yes</td></tr>

</table>

<p>Selenium WebDriver provides an API for interacting with these native JavaScript popup types. :contentReference[oaicite:2]{index=2}</p>

<hr>

<h2>6. Confirmation Alert vs Simple Alert</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>Simple Alert</th><th>Confirmation Alert</th></tr>

<tr><td>JavaScript Function</td><td><code>alert()</code></td><td><code>confirm()</code></td></tr>

<tr><td>Purpose</td><td>Display information.</td><td>Ask the user to confirm or cancel.</td></tr>

<tr><td>OK</td><td>Yes</td><td>Yes</td></tr>

<tr><td>Cancel</td><td>No separate Cancel choice.</td><td>Yes</td></tr>

<tr><td>Selenium Accept</td><td><code>accept()</code></td><td><code>accept()</code></td></tr>

<tr><td>Selenium Dismiss</td><td>Dismisses the alert.</td><td>Usually selects Cancel.</td></tr>

</table>

<hr>

<h2>7. Confirmation Alert vs Prompt</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>Confirmation Alert</th><th>Prompt</th></tr>

<tr><td>Function</td><td><code>confirm()</code></td><td><code>prompt()</code></td></tr>

<tr><td>OK</td><td>Yes</td><td>Yes</td></tr>

<tr><td>Cancel</td><td>Yes</td><td>Yes</td></tr>

<tr><td>Text Input</td><td>No</td><td>Yes</td></tr>

<tr><td>Accept</td><td><code>accept()</code></td><td><code>accept()</code></td></tr>

<tr><td>Cancel</td><td><code>dismiss()</code></td><td><code>dismiss()</code></td></tr>

<tr><td>Input Method</td><td>Not normally required</td><td><code>sendKeys()</code></td></tr>

</table>

<hr>

<h2>8. Selenium Alert Interface</h2>

<p>Selenium provides the <code>Alert</code> interface for interacting with native browser dialogs.</p>

<pre><code>Alert alert = driver.switchTo().alert();</code></pre>

<p>The main operations available for alert handling include accepting, dismissing, retrieving text, and sending input where supported. :contentReference[oaicite:3]{index=3}</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Method</th><th>Purpose</th></tr>

<tr><td><code>accept()</code></td><td>Accepts the currently displayed alert.</td></tr>

<tr><td><code>dismiss()</code></td><td>Dismisses the currently displayed alert.</td></tr>

<tr><td><code>getText()</code></td><td>Retrieves the text displayed by the alert in Selenium Java.</td></tr>

<tr><td><code>sendKeys()</code></td><td>Enters text into a prompt dialog.</td></tr>

</table>

<hr>

<h2>9. Switching to a Confirmation Alert</h2>

<p>Before interacting with a native confirmation alert, Selenium needs to switch to the active alert.</p>

<pre><code>Alert alert = driver.switchTo().alert();</code></pre>

<p>The basic workflow is:</p>

<pre><code>Click Button

     ↓

Confirmation Alert Appears

     ↓

driver.switchTo().alert()

     ↓

Alert Object

     ↓

getText()

     ↓

accept() / dismiss()</code></pre>

<p>Selenium's official Java examples use <code>driver.switchTo().alert()</code> to obtain the alert before interacting with it. :contentReference[oaicite:4]{index=4}</p>

<hr>

<h2>10. Accepting a Confirmation Alert</h2>

<p>The <code>accept()</code> method is used when the test should select the OK option.</p>

<pre><code>Alert alert = driver.switchTo().alert();

 

alert.accept();</code></pre>

<p>For a confirmation dialog, accepting normally corresponds to choosing <strong>OK</strong>. Selenium's alert API defines <code>accept()</code> as accepting the available alert dialog. :contentReference[oaicite:5]{index=5}</p>

<hr>

<h2>11. Dismissing a Confirmation Alert</h2>

<p>The <code>dismiss()</code> method is used when the test should select the Cancel option.</p>

<pre><code>Alert alert = driver.switchTo().alert();

 

alert.dismiss();</code></pre>

<p>For <code>confirm()</code> and <code>prompt()</code> dialogs, dismissing corresponds to choosing Cancel. :contentReference[oaicite:6]{index=6}</p>

<hr>

<h2>12. Reading Confirmation Alert Text</h2>

<p>The confirmation message can be read using <code>getText()</code> in Selenium Java.</p>

<pre><code>Alert alert = driver.switchTo().alert();

 

String message = alert.getText();

 

System.out.println("Alert Message: " + message);</code></pre>

<p>Reading the message is useful when the test needs to confirm that the correct warning or confirmation text is displayed.</p>

<hr>

<h2>13. Verifying Confirmation Alert Text</h2>

<p>A good automation test should validate the confirmation message before performing the confirmation action.</p>

<pre><code>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();</code></pre>

<p>This test verifies both the message and the user's confirmation action.</p>

<hr>

<h2>14. Complete Confirmation Alert Flow</h2>

<pre><code>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</code></pre>

<hr>

<h2>15. Basic Selenium Confirmation Alert Example</h2>

<pre><code>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();

    }

}</code></pre>

<hr>

<h2>16. Confirmation Alert with Text Validation</h2>

<pre><code>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();

    }

}</code></pre>

<hr>

<h2>17. Testing the OK Scenario</h2>

<p>The OK scenario verifies what happens when the user confirms the operation.</p>

<pre><code>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();</code></pre>

<p>After accepting the alert, the test should verify the expected application result.</p>

<hr>

<h2>18. Testing the Cancel Scenario</h2>

<p>The Cancel scenario verifies that the operation is not performed when the user rejects the confirmation.</p>

<pre><code>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();</code></pre>

<p>After dismissal, the test should verify that the original data or application state remains unchanged.</p>

<hr>

<h2>19. Confirmation Alert with Explicit Wait</h2>

<p>Confirmation alerts may not appear immediately after clicking a button. Selenium provides the <code>alertIsPresent()</code> expected condition for waiting until an alert becomes available.</p>

<pre><code>WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

wait.until(ExpectedConditions.alertIsPresent());

 

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

 

alert.accept();</code></pre>

<p>Selenium's current documentation demonstrates waiting with <code>ExpectedConditions.alertIsPresent()</code> before switching to and interacting with the alert. :contentReference[oaicite:7]{index=7}</p>

<hr>

<h2>20. Complete Example with Explicit Wait</h2>

<pre><code>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();

    }

}</code></pre>

<hr>

<h2>21. Why Explicit Wait is Important</h2>

<p>Suppose the application needs some time to execute JavaScript before showing the confirmation alert. If Selenium immediately calls <code>switchTo().alert()</code>, the alert may not yet be available.</p>

<pre><code>Click Delete

    ↓

JavaScript Processing

    ↓

Alert Appears

    ↓

Selenium Detects Alert

    ↓

Interact with Alert</code></pre>

<p>Using <code>alertIsPresent()</code> allows Selenium to wait for the required condition instead of relying on an arbitrary fixed delay.</p>

<hr>

<h2>22. Using Thread.sleep()</h2>

<p>A beginner may use <code>Thread.sleep()</code> to wait for a confirmation alert.</p>

<pre><code>driver.findElement(By.id("deleteButton")).click();

 

Thread.sleep(3000);

 

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

 

alert.accept();</code></pre>

<p>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.</p>

<hr>

<h2>23. Recommended Synchronization</h2>

<pre><code>driver.findElement(By.id("deleteButton")).click();

 

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

Alert alert = wait.until(

    ExpectedConditions.alertIsPresent()

);

 

alert.accept();</code></pre>

<hr>

<h2>24. NoAlertPresentException</h2>

<p>If Selenium attempts to access an alert when no alert is currently displayed, an alert-related exception can occur.</p>

<pre><code>Alert alert = driver.switchTo().alert();</code></pre>

<p>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}</p>

<pre><code>try {

 

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

 

    alert.accept();

 

} catch (NoAlertPresentException e) {

 

    System.out.println(

        "Confirmation alert was not present."

    );

}</code></pre>

<hr>

<h2>25. Handling an Optional Confirmation Alert</h2>

<p>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.</p>

<pre><code>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."

    );

}</code></pre>

<p>For a mandatory alert, however, silently continuing may hide an application defect. The expected behavior should be reflected in the test assertions and reporting.</p>

<hr>

<h2>26. Confirmation Alert After Delete</h2>

<p>Delete operations are one of the most common examples of confirmation dialogs.</p>

<pre><code>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();</code></pre>

<hr>

<h2>27. Confirmation Alert After Logout</h2>

<pre><code>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();</code></pre>

<p>After accepting, the test can verify that the application navigated to the login page or otherwise reflects the expected logged-out state.</p>

<hr>

<h2>28. Confirmation Alert for Order Cancellation</h2>

<pre><code>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();</code></pre>

<hr>

<h2>29. Canceling an Order Through the Alert</h2>

<pre><code>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."

);</code></pre>

<hr>

<h2>30. Confirmation Alert After Form Submission</h2>

<p>Important forms can display a confirmation alert before the submission is finalized.</p>

<pre><code>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();</code></pre>

<hr>

<h2>31. Confirmation Alert for Account Deactivation</h2>

<pre><code>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();</code></pre>

<hr>

<h2>32. Confirmation Alert vs HTML Modal</h2>

<p>A native JavaScript confirmation alert should not be confused with an HTML/CSS modal dialog.</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Native Confirmation Alert</th><th>HTML Modal</th></tr>

<tr><td>Created by JavaScript such as <code>confirm()</code>.</td><td>Created using HTML, CSS and JavaScript.</td></tr>

<tr><td>Handled using <code>Alert</code>.</td><td>Handled using <code>WebElement</code>.</td></tr>

<tr><td>Use <code>switchTo().alert()</code>.</td><td>Use normal locators.</td></tr>

<tr><td>Use <code>accept()</code> or <code>dismiss()</code>.</td><td>Click the modal's HTML buttons.</td></tr>

</table>

<h3>Native Confirmation</h3>

<pre><code>Alert alert = driver.switchTo().alert();

 

alert.accept();</code></pre>

<h3>HTML Modal</h3>

<pre><code>WebElement modal =

    driver.findElement(By.id("confirmationModal"));

 

WebElement confirmButton =

    modal.findElement(By.id("confirmButton"));

 

confirmButton.click();</code></pre>

<hr>

<h2>33. Common Mistake: Treating Alert as WebElement</h2>

<p>A native confirmation alert is not normally handled by locating an HTML element with XPath or CSS.</p>

<pre><code>// Incorrect for a native JavaScript confirmation

driver.findElement(

    By.xpath("//div[@class='alert']")

).click();</code></pre>

<p>Correct approach:</p>

<pre><code>Alert alert = driver.switchTo().alert();

 

alert.accept();</code></pre>

<hr>

<h2>34. Common Mistake: Using driver.accept()</h2>

<p>The <code>accept()</code> operation belongs to the Alert object.</p>

<pre><code>// Incorrect

driver.accept();</code></pre>

<p>Correct:</p>

<pre><code>Alert alert = driver.switchTo().alert();

 

alert.accept();</code></pre>

<hr>

<h2>35. Common Mistake: Using getText() on WebDriver</h2>

<pre><code>// Incorrect

String text = driver.getText();</code></pre>

<p>Correct:</p>

<pre><code>Alert alert = driver.switchTo().alert();

 

String text = alert.getText();</code></pre>

<hr>

<h2>36. Validating Dynamic Confirmation Messages</h2>

<p>Sometimes the alert message contains dynamic information, such as a username, product name, order number, or employee name.</p>

<pre><code>Alert alert = driver.switchTo().alert();

 

String message = alert.getText();

 

Assert.assertTrue(

    message.contains("Are you sure you want to delete")

);

 

alert.accept();</code></pre>

<p>Using <code>contains()</code> can be useful when only part of the message is stable.</p>

<hr>

<h2>37. Dynamic User Confirmation Example</h2>

<pre><code>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();</code></pre>

<hr>

<h2>38. Confirmation Alert in TestNG</h2>

<pre><code>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();

        }

    }

}</code></pre>

<hr>

<h2>39. TestNG Test for Cancel Operation</h2>

<pre><code>@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();

    }

}</code></pre>

<hr>

<h2>40. Confirmation Alert Utility Method</h2>

<p>In a large automation framework, common alert operations can be placed into reusable utility methods.</p>

<pre><code>public void acceptConfirmationAlert(WebDriver driver) {

 

    WebDriverWait wait =

        new WebDriverWait(

            driver,

            Duration.ofSeconds(10)

        );

 

    Alert alert = wait.until(

        ExpectedConditions.alertIsPresent()

    );

 

    alert.accept();

}</code></pre>

<hr>

<h2>41. Reusable Dismiss Alert Method</h2>

<pre><code>public void dismissConfirmationAlert(WebDriver driver) {

 

    WebDriverWait wait =

        new WebDriverWait(

            driver,

            Duration.ofSeconds(10)

        );

 

    Alert alert = wait.until(

        ExpectedConditions.alertIsPresent()

    );

 

    alert.dismiss();

}</code></pre>

<hr>

<h2>42. Reusable Alert Text Method</h2>

<pre><code>public String getConfirmationAlertText(WebDriver driver) {

 

    WebDriverWait wait =

        new WebDriverWait(

            driver,

            Duration.ofSeconds(10)

        );

 

    Alert alert = wait.until(

        ExpectedConditions.alertIsPresent()

    );

 

    return alert.getText();

}</code></pre>

<hr>

<h2>43. Using Alert Utility</h2>

<pre><code>driver.findElement(

    By.id("deleteButton")

).click();

 

String message =

    getConfirmationAlertText(driver);

 

Assert.assertTrue(

    message.contains("Are you sure")

);

 

acceptConfirmationAlert(driver);</code></pre>

<hr>

<h2>44. Confirmation Alerts with Page Object Model</h2>

<p>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.</p>

<pre><code>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();

    }

}</code></pre>

<p>Test class:</p>

<pre><code>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();</code></pre>

<hr>

<h2>45. Real-World Example: Delete Employee</h2>

<p>Consider an employee management application.</p>

<pre><code>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</code></pre>

<p>The automation should test both branches.</p>

<hr>

<h2>46. Employee Delete - Accept Test</h2>

<pre><code>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()

);</code></pre>

<hr>

<h2>47. Employee Delete - Cancel Test</h2>

<pre><code>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()

);</code></pre>

<hr>

<h2>48. Confirmation Alert Decision Table</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Scenario</th><th>User Action</th><th>Selenium Method</th><th>Expected Result</th></tr>

<tr><td>Confirm deletion</td><td>OK</td><td><code>accept()</code></td><td>Record is deleted.</td></tr>

<tr><td>Cancel deletion</td><td>Cancel</td><td><code>dismiss()</code></td><td>Record remains.</td></tr>

<tr><td>Confirm logout</td><td>OK</td><td><code>accept()</code></td><td>User is logged out.</td></tr>

<tr><td>Cancel logout</td><td>Cancel</td><td><code>dismiss()</code></td><td>User remains logged in.</td></tr>

<tr><td>Confirm order cancellation</td><td>OK</td><td><code>accept()</code></td><td>Order is cancelled.</td></tr>

<tr><td>Reject order cancellation</td><td>Cancel</td><td><code>dismiss()</code></td><td>Order remains active.</td></tr>

</table>

<hr>

<h2>49. Confirmation Alert and Multiple Dialogs</h2>

<p>An application can potentially produce dialogs sequentially. Each displayed dialog should be handled before the next interaction.</p>

<pre><code>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();</code></pre>

<hr>

<h2>50. Confirmation Alert Inside an IFrame</h2>

<p>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}</p>

<pre><code>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();</code></pre>

<hr>

<h2>51. Confirmation Alert vs Browser Window</h2>

<p>A confirmation alert is different from a new browser window or tab.</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Situation</th><th>Selenium Approach</th></tr>

<tr><td>JavaScript confirmation</td><td><code>driver.switchTo().alert()</code></td></tr>

<tr><td>New browser window/tab</td><td><code>driver.switchTo().window()</code></td></tr>

<tr><td>HTML modal</td><td><code>driver.findElement()</code></td></tr>

<tr><td>Iframe</td><td><code>driver.switchTo().frame()</code></td></tr>

</table>

<hr>

<h2>52. Confirmation Alert and unhandledPromptBehavior</h2>

<p>WebDriver also provides the <code>unhandledPromptBehavior</code> 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}</p>

<p>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.</p>

<hr>

<h2>53. Confirmation Alert and Test Synchronization</h2>

<pre><code>Click Action

     ↓

Application Processing

     ↓

JavaScript confirm()

     ↓

Alert Becomes Available

     ↓

alertIsPresent()

     ↓

switchTo().alert()

     ↓

getText()

     ↓

accept() / dismiss()

     ↓

Verify Application State</code></pre>

<hr>

<h2>54. Confirmation Alert and Application State</h2>

<p>Handling the alert is only one part of the test. After clicking OK or Cancel, the test should verify the resulting application state.</p>

<h3>After Accept</h3>

<pre><code>Delete Button

     ↓

Confirmation Alert

     ↓

accept()

     ↓

Record Deleted

     ↓

Verify Record Removed</code></pre>

<h3>After Dismiss</h3>

<pre><code>Delete Button

     ↓

Confirmation Alert

     ↓

dismiss()

     ↓

Delete Cancelled

     ↓

Verify Record Still Exists</code></pre>

<hr>

<h2>55. Confirmation Alert and Dynamic Applications</h2>

<p>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.</p>

<pre><code>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();</code></pre>

<hr>

<h2>56. Why Confirmation Alert Tests Can Fail</h2>

<ul>

<li>The test tries to access the alert before it appears.</li>

<li>The application does not trigger the alert.</li>

<li>The confirmation message has changed.</li>

<li>The popup is actually an HTML modal instead of a native JavaScript alert.</li>

<li>The test uses an inappropriate fixed wait.</li>

<li>The test does not verify the expected application state.</li>

<li>The wrong action is performed after the alert appears.</li>

</ul>

<hr>

<h2>57. How to Make Confirmation Alert Tests Stable</h2>

<ul>

<li>Use <code>WebDriverWait</code> for dynamically appearing alerts.</li>

<li>Use <code>ExpectedConditions.alertIsPresent()</code>.</li>

<li>Validate the alert text.</li>

<li>Test both OK and Cancel paths.</li>

<li>Verify the application state after the alert action.</li>

<li>Use reusable alert utilities in large frameworks.</li>

<li>Distinguish native alerts from HTML modals.</li>

<li>Avoid unnecessary hard-coded delays.</li>

</ul>

<hr>

<h2>58. Confirmation Alert Logging</h2>

<p>Logging the alert text can make debugging easier.</p>

<pre><code>Alert alert = wait.until(

    ExpectedConditions.alertIsPresent()

);

 

String message = alert.getText();

 

System.out.println(

    "Confirmation Alert: " + message

);

 

alert.accept();</code></pre>

<hr>

<h2>59. Confirmation Alert Regression Scenarios</h2>

<p>Whenever a business workflow containing a confirmation dialog changes, regression tests should verify the important branches of that workflow.</p>

<ul>

<li>Confirmation dialog appears.</li>

<li>Correct confirmation message is displayed.</li>

<li>OK confirms the operation.</li>

<li>Cancel prevents the operation.</li>

<li>Application state is correct after OK.</li>

<li>Application state is correct after Cancel.</li>

<li>Unexpected missing alerts are reported.</li>

</ul>

<hr>

<h2>60. Confirmation Alert Test Scenarios</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Test Scenario</th><th>Validation</th></tr>

<tr><td>Alert appears</td><td>Use <code>alertIsPresent()</code>.</td></tr>

<tr><td>Correct message</td><td>Use <code>getText()</code>.</td></tr>

<tr><td>User confirms</td><td>Use <code>accept()</code>.</td></tr>

<tr><td>User cancels</td><td>Use <code>dismiss()</code>.</td></tr>

<tr><td>Alert missing</td><td>Report the expected behavior failure.</td></tr>

<tr><td>Wrong message</td><td>Fail message validation.</td></tr>

<tr><td>Action succeeds</td><td>Verify resulting application state.</td></tr>

<tr><td>Action cancelled</td><td>Verify original state remains.</td></tr>

</table>

<hr>

<h2>61. Confirmation Alert Exception Reporting</h2>

<pre><code>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."

    );

}</code></pre>

<hr>

<h2>62. Mini Project: Employee Management Confirmation Alert</h2>

<p>Create automated tests for an employee management application where deleting an employee requires confirmation.</p>

<h3>Application Flow</h3>

<pre><code>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</code></pre>

<hr>

<h2>63. Mini Project Test Cases</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Test Case</th><th>Expected Result</th></tr>

<tr><td>Verify alert appears</td><td>Confirmation alert is displayed.</td></tr>

<tr><td>Verify alert message</td><td>Expected confirmation text is displayed.</td></tr>

<tr><td>Accept deletion</td><td>Employee is deleted.</td></tr>

<tr><td>Cancel deletion</td><td>Employee remains available.</td></tr>

<tr><td>Verify synchronization</td><td>Test waits for the alert.</td></tr>

<tr><td>Verify unexpected alert absence</td><td>Test reports the problem.</td></tr>

</table>

<hr>

<h2>64. Complete Mini Project Example</h2>

<pre><code>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();

        }

    }

}</code></pre>

<hr>

<h2>65. Confirmation Alert Framework Design</h2>

<pre><code>Automation Framework

        |

        +-- Page Objects

        |

        +-- Test Classes

        |

        +-- Alert Utility

        |      |

        |      +-- waitForAlert()

        |      +-- getAlertText()

        |      +-- acceptAlert()

        |      +-- dismissAlert()

        |

        +-- Wait Utility

        |

        +-- Assertions

        |

        +-- Reporting</code></pre>

<hr>

<h2>66. Alert Utility Class</h2>

<pre><code>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();

    }

}</code></pre>

<hr>

<h2>67. Using Alert Utility Class</h2>

<pre><code>driver.findElement(

    By.id("deleteButton")

).click();

 

String message =

    AlertUtility.getText(driver, 10);

 

Assert.assertTrue(

    message.contains("Are you sure")

);

 

AlertUtility.accept(driver, 10);</code></pre>

<hr>

<h2>68. Best Practices for Confirmation Alerts</h2>

<ul>

<li>Use the <code>Alert</code> interface for native JavaScript confirmation dialogs.</li>

<li>Use <code>switchTo().alert()</code> to access the active alert.</li>

<li>Use <code>getText()</code> to validate the displayed message.</li>

<li>Use <code>accept()</code> for the OK/confirm scenario.</li>

<li>Use <code>dismiss()</code> for the Cancel scenario.</li>

<li>Use <code>alertIsPresent()</code> when alert timing is dynamic.</li>

<li>Test both confirmation and cancellation paths.</li>

<li>Verify the application state after handling the alert.</li>

<li>Do not use XPath or CSS locators for a native JavaScript alert.</li>

<li>Use reusable utility methods in larger automation frameworks.</li>

<li>Do not silently ignore a missing alert when the alert is mandatory for the workflow.</li>

</ul>

<hr>

<h2>69. Common Mistakes</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Mistake</th><th>Correct Approach</th></tr>

<tr><td>Using XPath for a native confirmation alert</td><td>Use <code>switchTo().alert()</code>.</td></tr>

<tr><td>Calling <code>driver.accept()</code></td><td>Switch to Alert and call <code>accept()</code>.</td></tr>

<tr><td>Calling <code>driver.getText()</code></td><td>Use <code>alert.getText()</code>.</td></tr>

<tr><td>Always using <code>Thread.sleep()</code></td><td>Prefer explicit waits.</td></tr>

<tr><td>Testing only OK</td><td>Test both <code>accept()</code> and <code>dismiss()</code>.</td></tr>

<tr><td>Not validating alert text</td><td>Use <code>getText()</code> and assertions.</td></tr>

<tr><td>Using Alert API for an HTML modal</td><td>Use WebElement locators for the HTML modal.</td></tr>

<tr><td>Not verifying final state</td><td>Assert the result after handling the alert.</td></tr>

</table>

<hr>

<h2>70. Confirmation Alert Checklist</h2>

<ul>

<li>Identify whether the popup is a native JavaScript confirmation.</li>

<li>Identify the action that triggers the alert.</li>

<li>Click or perform the triggering action.</li>

<li>Wait for the alert when required.</li>

<li>Switch to the alert.</li>

<li>Read the confirmation message.</li>

<li>Validate the expected message.</li>

<li>Test the OK scenario using <code>accept()</code>.</li>

<li>Test the Cancel scenario using <code>dismiss()</code>.</li>

<li>Verify the application state after each action.</li>

<li>Handle exceptions appropriately.</li>

<li>Use reusable alert utilities when appropriate.</li>

</ul>

<hr>

<h2>71. Interview Question: What is a Confirmation Alert?</h2>

<p>A confirmation alert is a native JavaScript dialog generally created using <code>confirm()</code>. It asks the user whether an operation should proceed and normally provides OK and Cancel choices.</p>

<hr>

<h2>72. Interview Question: How do you handle a Confirmation Alert in Selenium?</h2>

<pre><code>Alert alert = driver.switchTo().alert();

 

alert.accept();</code></pre>

<p>For Cancel:</p>

<pre><code>Alert alert = driver.switchTo().alert();

 

alert.dismiss();</code></pre>

<hr>

<h2>73. Interview Question: What is the Difference Between accept() and dismiss()?</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Method</th><th>Purpose</th></tr>

<tr><td><code>accept()</code></td><td>Accepts the alert; for a confirmation dialog this normally selects OK.</td></tr>

<tr><td><code>dismiss()</code></td><td>Dismisses the alert; for a confirmation dialog this normally selects Cancel.</td></tr>

</table>

<hr>

<h2>74. Interview Question: How do you Get the Text of a Confirmation Alert?</h2>

<pre><code>Alert alert = driver.switchTo().alert();

 

String text = alert.getText();</code></pre>

<hr>

<h2>75. Interview Question: Can XPath be Used for a Native Confirmation Alert?</h2>

<p>No. A native JavaScript confirmation dialog is handled through Selenium's Alert API rather than normal DOM locators.</p>

<hr>

<h2>76. Interview Question: How do you Wait for a Confirmation Alert?</h2>

<pre><code>WebDriverWait wait =

    new WebDriverWait(

        driver,

        Duration.ofSeconds(10)

    );

 

Alert alert = wait.until(

    ExpectedConditions.alertIsPresent()

);</code></pre>

<hr>

<h2>77. Interview Question: What Exception Can Occur if No Alert is Present?</h2>

<p>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 <code>NoAlertPresentException</code>.</p>

<hr>

<h2>78. Interview Question: What is alertIsPresent()?</h2>

<p><code>alertIsPresent()</code> is an expected condition used with an explicit wait to wait until a browser alert is available.</p>

<hr>

<h2>79. Interview Question: What is the Difference Between a JavaScript Confirmation and an HTML Modal?</h2>

<p>A JavaScript confirmation is handled using Selenium's <code>Alert</code> API, while an HTML modal is part of the page DOM and is generally handled using WebElement locators.</p>

<hr>

<h2>80. Interview Question: Why Should Both OK and Cancel be Tested?</h2>

<p>Because the application can execute different business logic depending on the user's choice. Testing both paths verifies both confirmation and cancellation behavior.</p>

<hr>

<h2>81. Interview Question: Can Confirmation Alert Text be Validated?</h2>

<p>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}</p>

<hr>

<h2>82. Interview Question: Can sendKeys() be Used with a Confirmation Alert?</h2>

<p><code>sendKeys()</code> is primarily used with a prompt dialog because a prompt provides a text-input area. A normal confirmation dialog does not require text input.</p>

<hr>

<h2>83. Interview Question: Why Use WebDriverWait Instead of Thread.sleep()?</h2>

<p><code>WebDriverWait</code> waits for a specific condition such as an alert becoming present, whereas <code>Thread.sleep()</code> pauses for a fixed amount of time regardless of whether the alert is ready.</p>

<hr>

<h2>84. Quick Revision Table</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Requirement</th><th>Selenium Code</th></tr>

<tr><td>Switch to alert</td><td><code>driver.switchTo().alert()</code></td></tr>

<tr><td>Read alert text</td><td><code>alert.getText()</code></td></tr>

<tr><td>Click OK</td><td><code>alert.accept()</code></td></tr>

<tr><td>Click Cancel</td><td><code>alert.dismiss()</code></td></tr>

<tr><td>Wait for alert</td><td><code>ExpectedConditions.alertIsPresent()</code></td></tr>

<tr><td>Handle no alert</td><td><code>NoAlertPresentException</code></td></tr>

<tr><td>Wait dynamically</td><td><code>WebDriverWait</code></td></tr>

</table>

<hr>

<h2>85. Confirmation Alert Cheat Sheet</h2>

<pre><code>// 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();</code></pre>

<hr>

<h2>86. Recommended Learning Sequence</h2>

<ol>

<li>Understand JavaScript <code>confirm()</code>.</li>

<li>Understand the difference between alert, confirm, and prompt.</li>

<li>Learn the Selenium <code>Alert</code> interface.</li>

<li>Learn <code>switchTo().alert()</code>.</li>

<li>Learn <code>getText()</code>.</li>

<li>Learn <code>accept()</code>.</li>

<li>Learn <code>dismiss()</code>.</li>

<li>Learn explicit waits.</li>

<li>Learn <code>alertIsPresent()</code>.</li>

<li>Automate OK scenarios.</li>

<li>Automate Cancel scenarios.</li>

<li>Add assertions.</li>

<li>Create reusable alert utilities.</li>

<li>Integrate alert handling into a Selenium framework.</li>

</ol>

<hr>

<h2>87. Common Errors and Solutions</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Error/Problem</th><th>Possible Cause</th><th>Solution</th></tr>

<tr><td><code>NoAlertPresentException</code></td><td>Alert is not available.</td><td>Wait for the alert and verify the triggering action.</td></tr>

<tr><td>Unable to locate alert with XPath</td><td>Native alert is not handled as a normal DOM element.</td><td>Use <code>switchTo().alert()</code>.</td></tr>

<tr><td>Random test failures</td><td>Synchronization problem.</td><td>Use <code>alertIsPresent()</code>.</td></tr>

<tr><td>Cancel path not tested</td><td>Only OK scenario was automated.</td><td>Add a <code>dismiss()</code> scenario.</td></tr>

<tr><td>Wrong alert message</td><td>Expected text does not match actual text.</td><td>Validate and update the test according to the application's expected behavior.</td></tr>

<tr><td>Alert API does not work</td><td>Popup may be an HTML modal.</td><td>Inspect the popup and use WebElement locators if it is DOM-based.</td></tr>

</table>

<hr>

<h2>88. Final Summary</h2>

<p>Confirmation Alerts are native JavaScript dialogs that ask users to confirm or cancel an operation. They are commonly created using JavaScript's <code>confirm()</code> function and normally provide OK and Cancel choices.</p>

<p>In Selenium WebDriver, confirmation alerts are handled using the <code>Alert</code> 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 <code>accept()</code> or <code>dismiss()</code>. Selenium's official documentation demonstrates this same approach for confirmation dialogs. :contentReference[oaicite:12]{index=12}</p>

<pre><code>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</code></pre>

<p>The most important Selenium methods to remember are:</p>

<ul>

<li><code>driver.switchTo().alert()</code> – accesses the active native alert.</li>

<li><code>alert.getText()</code> – retrieves the confirmation message.</li>

<li><code>alert.accept()</code> – accepts the confirmation.</li>

<li><code>alert.dismiss()</code> – dismisses the confirmation.</li>

<li><code>ExpectedConditions.alertIsPresent()</code> – waits for an alert to become available.</li>

</ul>

<hr>

<h2>89. Selenium Training Resources</h2>

<p>For detailed Selenium WebDriver training covering locators, waits, alerts, TestNG, Page Object Model, automation frameworks, and practical testing, visit <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training</a>.</p>

<p>To explore the course through a demo session, visit <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a>.</p>

</div>

Previous Next
whatsapp