Software Development

Effective Ways to Handle Alerts and Popups in Selenium

Popups and alerts are common elements in web applications used to capture user input, provide notifications, or confirm actions. Managing these effectively is crucial for seamless automated testing using Selenium WebDriver. In this article, we will explore how to handle popups and different types of alerts encountered during web application testing, including examples and best practices for handling them with Selenium.

1. What is an Alert/Popup?

An alert or popup is a message box displayed by a browser or web application to notify users or request input. These can be triggered by JavaScript functions or web application events and are typically used for:

  • Displaying information.
  • Confirming user actions.
  • Capturing user input.

2. What are the Different Types of Alerts/Popups?

In web application testing, the following types of alerts and popups are commonly encountered:

Simple Alert

A basic message with an “OK” button, triggered using JavaScript’s alert() method.

Screenshot of a simple alert - Java Selenium handling alerts and popups.

Confirmation Alert
Asks for confirmation with “OK” and “Cancel” buttons, triggered using JavaScript’s confirm() method.

Screenshot of a confirmation alert - Java Selenium handling alerts and popups.

Prompt Alert
Allows user input via a text field and provides “OK” and “Cancel” buttons, triggered using JavaScript’s prompt() method.

Screenshot of a prompt - Java Selenium handling alerts and popups.

Web Dialog Box/Popup Window
A custom modal or new browser window triggered by the application, typically styled using HTML/CSS.

Screenshot of a custom dialog box - Java Selenium handling alerts and popups.

3. Adding Dependencies for Selenium

Before working with Selenium WebDriver, we need to include the required dependencies in our project. Selenium provides libraries and drivers to interact with browsers. Below are the necessary dependencies for Maven projects.

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.23.1</version>
        </dependency>
        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>5.9.2</version>
        </dependency>

Make sure to use the latest stable version to get the newest features and fixes.

4. HTML Code for Popups and Alerts

To demonstrate how to handle various types of alerts and popups, we will use the following HTML file. Save it as popup-demo.html to test the examples locally.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Popup and Alert Demo</title>
        <script>
            // JavaScript function to trigger an alert
            function showAlert() {
                alert("This is a simple alert!");
            }

            // JavaScript function to trigger a confirmation alert
            function showConfirm() {
                if (confirm("Do you confirm this action?")) {
                    document.getElementById("confirmationMessage").innerText = "You clicked OK!";
                } else {
                    document.getElementById("confirmationMessage").innerText = "You clicked Cancel!";
                }
            }

            // JavaScript function to trigger a prompt alert
            function showPrompt() {
                var name = prompt("Please enter your name:");
                if (name !== null) {
                    document.getElementById("promptMessage").innerText = "Hello " + name + "! How are you today?";
                }
            }

            // JavaScript to open a dialog
            function openDialog() {
                document.getElementById("dialog").style.display = "block";
            }

            // JavaScript to close a dialog
            function closeDialog() {
                document.getElementById("dialog").style.display = "none";
            }
        </script>
        <style>
            /* Basic styling for the dialog box */
            #dialog {
                display: none;
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background-color: #fff;
                padding: 20px;
                border: 1px solid #ccc;
                box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
                margin: auto;
                width: 50%;
            }
            #dialog button {
                padding: 10px 15px;
                background-color: #007bff;
                color: #fff;
                border: none;
                border-radius: 4px;
                cursor: pointer;
            }

            #dialog button:hover {
                background-color: #0056b3;
            }
        </style>
    </head>
    <body>
        <h1>Popup and Alert Demo</h1>

        <!-- Alert example -->
        <button id="simpleAlertButton" onclick="showAlert()">Show Alert</button>

        <!-- Confirmation alert example -->
        <button id="confirmAlertButton" onclick="showConfirm()">Show Confirmation</button>
        <p id="confirmationMessage"></p>

        <!-- Prompt alert example -->
        <button id="promptAlertButton" onclick="showPrompt()">Show Prompt</button>
        <p id="promptMessage"></p>

        <!-- Dialog box example -->
        <button onclick="openDialog()">Open Dialog</button>
        <div id="dialog">
            <h2>Custom Dialog Box</h2>

            <button onclick="closeDialog()" id="closeModal">Close</button>
        </div>

    </body>
</html>

This code provides examples of simple alerts, confirmation alerts, prompt alerts and a custom dialog box.

5. How to Handle Alerts in Selenium WebDriver

To effectively interact with alerts in Selenium WebDriver, we first need to set up our test environment. This involves initializing the WebDriver, navigating to the target webpage, and ensuring a clean state by deleting all cookies before starting each test.

5.1 Handling Simple Alerts

Use Selenium’s switchTo().alert() to interact with simple alerts. Below, we demonstrate how to handle a simple alert, from triggering it on the webpage to capturing its message and verifying its behavior.

public class SeleniumAlertsPopupsTest {

    private WebDriver driver;

    @BeforeEach
    public void setup() {
        WebDriverManager.chromedriver().setup();
        driver = new ChromeDriver();
        driver.manage().deleteAllCookies();
        driver.get("file:///Users/omozegieaziegbe/Development/selenium-alerts-popups/src/main/resources/popup-demo.html");
    }

    @Test
    public void handleSimpleAlert() {
        // Trigger the simple alert
        driver.findElement(By.id("simpleAlertButton")).click();
               
        // Handle the alert
        Alert alert = driver.switchTo().alert();
        String alertText = alert.getText();
        alert.accept();
        assertEquals("This is a simple alert!", alertText); 
    }

}

In this code, the setup method ensures the WebDriver is properly initialized and ready for use by setting up ChromeDriver and deleting all cookies to prevent any leftover data from interfering with tests. The browser navigates to the HTML file containing the alert demo.

The test method handleSimpleAlert then interacts with a simple alert by locating and clicking the button that triggers the alert. Selenium’s switchTo().alert() handles the alert, allowing us to retrieve its message using getText() and accept the alert using accept(). Finally, we assert that the alert’s text matches the expected message to validate the behavior.

5.2 Handling Confirmation Alerts

Handling confirmation alerts in Selenium involves interacting with popups that prompt the user to confirm or cancel an action. These alerts typically display a message and provide two options: “OK” and “Cancel.” In the following code, we demonstrate how to trigger a confirmation alert, validate its text, accept or dismiss it, and verify the resulting actions displayed on the webpage.

    @Test
    public void handleConfirmationAlert() {
        WebElement element = driver.findElement(By.id("confirmAlertButton"));

        // Trigger the confirmation alert using JavascriptExecutor
        ((JavascriptExecutor) driver).executeScript("arguments[0].click()", element);

        // Switch to the alert and get its text
        Alert confirmationAlert = driver.switchTo().alert();
        String alertText = confirmationAlert.getText();

        // Assert the alert text
        Assertions.assertEquals("Do you confirm this action?", alertText);

        confirmationAlert.accept();

        String confirmationMessage = driver.findElement(By.id("confirmationMessage")).getText();
        Assertions.assertEquals("You clicked OK!", confirmationMessage);

        driver.findElement(By.id("confirmAlertButton")).click();
        confirmationAlert = driver.switchTo().alert();
        confirmationAlert.dismiss();

        String cancelMessage = driver.findElement(By.id("confirmationMessage")).getText();
        Assertions.assertEquals("You clicked Cancel!", cancelMessage);
    }

In this test, the confirmation alert is triggered by clicking the “Confirm Alert” button using a JavascriptExecutor to ensure compatibility. The alert is handled using driver.switchTo().alert(), allowing us to retrieve and assert its displayed text. The alert is then accepted using accept(), and the webpage’s response is validated by asserting the message displayed after clicking “OK.”

The process is repeated to test the dismiss functionality, where the alert is dismissed using dismiss(), and the corresponding cancellation message is asserted.

5.3 How to Handle Prompt Alerts

Prompt alerts in web applications are used to collect user input directly through a popup box. They allow users to input text, which can then be processed by the application. In the following test, we demonstrate how to handle a prompt alert in Selenium, including triggering the alert, interacting with it by sending text, and validating the subsequent behavior of the application.

    @Test
    public void handlePromptAlert() {

        WebElement element = driver.findElement(By.id("promptAlertButton"));

        ((JavascriptExecutor) driver).executeScript("arguments[0].click()", element);

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

        String alertText = promptAlert.getText();
        Assertions.assertEquals("Please enter your name:", alertText);
        promptAlert.sendKeys("Test User");
        promptAlert.accept();


        // Verify the message displayed after interacting with the prompt
        String confirmationMessage = driver.findElement(By.id("promptMessage")).getText();
        Assertions.assertEquals("Hello Test User! How are you today?", confirmationMessage);
    }

This test begins by locating the “Prompt Alert” button and triggering the alert using a JavascriptExecutor. The switchTo().alert() method switches the driver’s focus to the prompt alert, where the alert’s text is retrieved and asserted for correctness. Next, user input is simulated by sending the text “Test User” to the alert using sendKeys(), and the alert is accepted with accept(). Finally, the webpage’s response is verified by asserting the text displayed after the alert interaction, confirming that the input was processed correctly.

5.4 Handling Web Dialog Boxes or Popups

Web dialog boxes are distinct from JavaScript alerts. Dialog boxes often take the form of modal windows or custom popups that overlay the main page, requiring interaction before accessing the rest of the page. Selenium’s ExpectedConditions can be used to wait for these modals and interact with them.

    @Test
    public void handleDialogBoxes() {
    // Click the "Open Dialog" button to make the dialog visible
    WebElement openDialogButton = driver.findElement(By.xpath("//button[text()='Open Dialog']"));
    openDialogButton.click();

    // Wait for the dialog to appear
    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10), Duration.ofMillis(500));
    WebElement dialog = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("dialog")));

    // Locate and click the "Close" button in the dialog
    WebElement closeButton = driver.findElement(By.id("closeModal"));
    closeButton.click();

    // Wait until the dialog is closed
    boolean isDialogClosed = wait.until(ExpectedConditions.invisibilityOf(dialog));
    assertTrue(isDialogClosed, "The dialog should be closed after clicking the close button");
    }

The test starts by clicking the “Open Dialog” button, triggering the openDialog() JavaScript function to set the dialog’s display property to block. Using WebDriverWait with ExpectedConditions.visibilityOfElementLocated, we ensure the dialog is visible before interacting with it. Next, the “Close” button inside the dialog is clicked, which calls the closeDialog() function to set the display property to none. Finally, we verify that the dialog is closed by waiting for its invisibility using ExpectedConditions.invisibilityOf and asserting the result.

6. Conclusion

In this article, we covered the handling of different alert types such as simple alerts, confirmation alerts, and prompt alerts, showing how to interact with them programmatically using Selenium’s Alert interface. We also discussed how Java Selenium can handle alerts and popups, providing practical examples and test scenarios. Through these insights, we demonstrated how to automate web interactions involving alerts and popups, ensuring efficient and reliable test automation workflows.

7. Download the Source Code

This article explored how to handle alerts and popups in Java Selenium.

Download
You can download the full source code of this example here: Java selenium handle alerts popups

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button