How to Handle Alerts & Popups in Selenium?

โšก Smart Summary

Alerts and popups in Selenium are JavaScript dialogs and child windows that block automation flow. This article explains how to identify simple, prompt, and confirmation alerts, switch into them with WebDriver, and manage multiple windows using getWindowHandles().

  • ๐Ÿ”” Core Definition: A Selenium alert is a JavaScript dialog rendered above the page that must be handled before further actions.
  • ๐Ÿ—‚๏ธ Three Alert Types: Simple (info), Prompt (text input), and Confirmation (Yes/No) each require different WebDriver calls.
  • ๐Ÿ› ๏ธ Alert API: Use driver.switchTo().alert() with accept(), dismiss(), getText(), and sendKeys() to interact with the dialog.
  • ๐ŸชŸ Window Handling: getWindowHandle() returns the current window ID; getWindowHandles() returns the full Set for switching.
  • ๐Ÿš€ Selenium 4 Note: Selenium Manager auto-resolves drivers, removing the need for hard-coded chromedriver.exe paths.
  • ๐Ÿค– AI Assistance: AI agents generate locator-aware alert and window scripts, reducing manual scaffolding in test suites.

How to Handle Alerts & Popups in Selenium

What is an Alert in Selenium?

An Alert in Selenium is a small JavaScript dialog box that appears on the screen to give the user some information or notification. It can confirm a specific action, request permission to perform an operation, or display a warning message.

In this tutorial, you will learn how to handle popups in Selenium and the different types of alerts found in web application testing. We will also see how to handle an alert in Selenium WebDriver and how to accept or reject it depending on the alert type.

Types of Alerts in Selenium

JavaScript exposes three alert dialogs that Selenium must handle differently.

1) Simple Alert

The simple alert displays information or a warning on screen. The user can only acknowledge it by clicking OK.

Simple alert dialog example in browser

2) Prompt Alert

The prompt alert asks the user for input. Selenium WebDriver can type into it using sendKeys("input...").

Prompt alert dialog with input field

3) Confirmation Alert

The confirmation alert asks the user to approve or cancel an operation. It exposes both OK and Cancel buttons.

Confirmation alert dialog with OK and Cancel buttons

How to Handle an Alert in Selenium WebDriver

The Alert interface in Selenium WebDriver exposes four methods that cover every alert interaction.

  1. void dismiss() โ€” clicks the Cancel button.
driver.switchTo().alert().dismiss();
  1. void accept() โ€” clicks the OK button.
driver.switchTo().alert().accept();
  1. String getText() โ€” captures the alert message.
driver.switchTo().alert().getText();
  1. void sendKeys(String stringToSend) โ€” types text into a prompt alert.
driver.switchTo().alert().sendKeys("Text");

Eclipse autocomplete shows the available alert methods after typing alert. on the editor line. Switch from the main window into the alert at any time using Selenium’s .switchTo() method.

Eclipse autocomplete showing alert handling methods

Worked Example: Delete Customer Demo

Let us automate the following scenario. We will use the Guru99 demo site to illustrate Selenium alert handling.

Step 1) Launch the browser and open https://demo.guru99.com/test/delete_customer.php.

Step 2) Enter any Customer ID.

Delete Customer demo page with Customer ID field

Step 3) Click the Submit button.

Submit button to trigger confirmation alert

Step 4) Accept or dismiss the resulting confirmation alert.

Confirmation alert triggered by delete action

Selenium Java Code: Handle Confirmation Alert

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.Alert;

public class AlertDemo {

    public static void main(String[] args) throws NoAlertPresentException, InterruptedException {
        // Selenium 4 ships Selenium Manager, so an explicit driver path is no longer required.
        WebDriver driver = new ChromeDriver();

        // Open the Delete Customer demo page
        driver.get("https://demo.guru99.com/test/delete_customer.php");

        driver.findElement(By.name("cusid")).sendKeys("53920");
        driver.findElement(By.name("submit")).submit();

        // Switch to the confirmation alert
        Alert alert = driver.switchTo().alert();

        // Capture the alert message
        String alertMessage = alert.getText();
        System.out.println(alertMessage);
        Thread.sleep(5000);

        // Accept the alert
        alert.accept();

        driver.quit();
    }
}

Output: The browser opens the Delete Customer page, submits the customer ID, accepts the confirmation alert, and removes the record from the demo application.

How to Handle Popup Windows in Selenium WebDriver

When automation must work across multiple browser windows, the test has to switch focus between them and return to the parent window after each operation. Selenium WebDriver exposes two methods that make this possible.

driver.getWindowHandles()

Returns a Set<String> of every open window handle. Iterate over the set to switch from the main window to any child window in the application.

driver.getWindowHandle()

Returns a String with the unique handle of the current window. Capture this before opening any child window so you can return to the parent later.

Follow these steps to demonstrate window handling against the Guru99 popup demo.

Worked Example: Window Switching

Step 1) Launch the browser and open https://demo.guru99.com/popup.php.

Guru99 popup demo landing page

Step 2) Click the Click Here link. A new child window opens.

Child window opening from the Click Here link

Step 3) The child window prompts the user to enter an email ID and submit.

Child window email input form

Step 4) Enter the email ID and submit.

Email submission inside the child window

Step 5) The page displays the access credentials returned by the demo.

Access credentials displayed in the child window

After the credentials display:

  1. Close the child window.

Closing the child window in the browser

  1. Switch focus back to the parent window.

Switching focus back to the parent window

Selenium Java Code: Handle Multiple Windows

import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class WindowHandle_Demo {

    public static void main(String[] args) throws InterruptedException {
        // Selenium 4 auto-resolves the browser driver via Selenium Manager
        WebDriver driver = new FirefoxDriver();

        driver.get("https://demo.guru99.com/popup.php");
        driver.manage().window().maximize();

        driver.findElement(By.xpath("//*[contains(@href,'popup.php')]")).click();

        String mainWindow = driver.getWindowHandle();

        // Capture every open window handle
        Set<String> allWindows = driver.getWindowHandles();
        Iterator<String> iterator = allWindows.iterator();

        while (iterator.hasNext()) {
            String childWindow = iterator.next();

            if (!mainWindow.equalsIgnoreCase(childWindow)) {
                // Switch to the child window
                driver.switchTo().window(childWindow);
                driver.findElement(By.name("emailid")).sendKeys("gaurav.3n@gmail.com");
                driver.findElement(By.name("btnLogin")).click();

                // Close the child window
                driver.close();
            }
        }
        // Return focus to the main window
        driver.switchTo().window(mainWindow);
        driver.quit();
    }
}

Output: The site launches, the Click here link opens a child tab, Selenium enters the email and submits, closes the child window, and returns to the parent.

Multiple window handling completed in Selenium

Conclusion

  • Defined the three Selenium alert types โ€” simple, prompt, and confirmation โ€” with a screenshot for each.
  • Demonstrated alert handling with the WebDriver Alert interface using a working delete-customer scenario.
  • Handled multiple browser windows by capturing handles with getWindowHandle() and getWindowHandles() and switching between them.

FAQs

An alert is a native JavaScript dialog that suspends the page until handled. A popup window is a new browser window or tab. Alerts use switchTo().alert(); popups use switchTo().window() with the handle returned by getWindowHandles().

NoAlertPresentException is thrown when switchTo().alert() runs but no alert is currently displayed. Wrap the call with WebDriverWait until ExpectedConditions.alertIsPresent() is true to give the page time to trigger the dialog.

Basic-auth popups are not standard JavaScript alerts. Pass credentials in the URL (https://user:pass@site.com) or use Selenium 4 CDP Network.setExtraHTTPHeaders. For SSO popups, use BrowserStack or a registered hasAuthentication handler.

AI assistants such as AI code copilots generate locator-aware alert handlers, predict required waits, and refactor brittle XPath. They also draft assertions for alert text and child window URLs, accelerating Selenium test creation.

Yes. Self-healing test platforms use AI to detect DOM changes, swap broken locators, and adjust waits when alerts or popups shift. This reduces maintenance for Selenium suites running against frequently updated front ends.

Summarize this post with: