How to Handle Browser Pop-ups and Alerts in Selenium with Java

How to Handle Browser Pop-ups and Alerts in Selenium with Java

When you’re working with Selenium WebDriver in Java, you’ll often encounter situations where your automation script has to deal with browser pop-ups or JavaScript alerts. If these pop-ups aren't handled properly, your script might fail or get stuck.


In this blog, we’ll cover everything you need to know about handling browser pop-ups and alerts effectively using Selenium with Java.


Types of Browser Pop-ups You Might Encounter

JavaScript Alerts

These are simple pop-up alerts generated by JavaScript. They can be:


Alert box (simple OK button)


Confirmation box (OK and Cancel buttons)


Prompt box (Input field + OK/Cancel buttons)


Browser-based Pop-ups

These are authentication windows triggered by the browser itself (e.g., username/password pop-ups).


HTML-based Modals

These are part of the web page, created using HTML/CSS/JavaScript (not real browser alerts).


Handling JavaScript Alerts with Selenium

Selenium provides a simple way to switch to an alert and interact with it using the Alert interface.


Step-by-Step Example:

First, make sure you import:


java

Copy

Edit

import org.openqa.selenium.Alert;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

Code Example:

java

Copy

Edit

public class AlertHandlingExample {

    public static void main(String[] args) {

        // Setup ChromeDriver (Make sure you set the correct path)

        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        WebDriver driver = new ChromeDriver();


        try {

            driver.get("https://example.com/alert-page");


            // Assume a button triggers an alert

            driver.findElement(By.id("alertButton")).click();


            // Switch to the alert

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


            // Get alert text

            System.out.println("Alert message: " + alert.getText());


            // Accept the alert (click OK)

            alert.accept();


            // If you want to dismiss instead of accept (for Confirm pop-ups)

            // alert.dismiss();


            // For prompt boxes: send text

            // alert.sendKeys("Your input here");

            // alert.accept();


        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            driver.quit();

        }

    }

}

Key Alert Methods You Should Know


Method Description

alert.accept() Clicks the OK button on the alert

alert.dismiss() Clicks the Cancel button

alert.getText() Retrieves the alert message

alert.sendKeys("text") Sends text input to a prompt alert

Handling Browser Authentication Pop-ups

Browser authentication pop-ups (like HTTP basic auth) are not handled by Alert.

Solution: You can pass username and password directly in the URL!


Example:

java

Copy

Edit

driver.get("https://username:password@the-internet.herokuapp.com/basic_auth");

Note: Some modern browsers block this technique for security reasons. In that case, you may need to use tools like AutoIT (for Windows) or Robot Class.


Handling HTML-based Modals (Not True Alerts)

If the pop-up is a modal dialog built with HTML, you treat it like any other web element.

Just find the modal’s elements with Selenium locators (By.id, By.className, By.xpath, etc.) and interact with them.


Example:


java

Copy

Edit

driver.findElement(By.id("closeModalButton")).click();

Pro Tips for Handling Pop-ups Smoothly

Always add explicit waits before switching to an alert to avoid NoAlertPresentException.


Example:


java

Copy

Edit

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

wait.until(ExpectedConditions.alertIsPresent());

Always handle alerts before doing any other action on the page after an alert appears.


Test different alert types separately: simple alerts, confirm dialogs, and prompts.


Conclusion

Handling pop-ups and alerts is a fundamental skill in Selenium automation.

By mastering alert handling with simple methods like switchTo().alert(), accept(), dismiss(), and sendKeys(), you’ll be able to create stable, error-free test scripts even when unexpected browser pop-ups appear.


Next Step: Try creating a mini project where you automate a page with all three types of alerts!

Learn Selenium JAVA Course

Read More

Locators in Selenium: Finding Elements Effectively

Setting Up Selenium WebDriver in Java: A Step-by-Step Guide

Visit Our IHUB Talent Training in Hyderabad

Get Directions

Comments

Popular posts from this blog

How to Install and Set Up Selenium in Python (Step-by-Step)

Feeling Stuck in Manual Testing? Here’s Why You Should Learn Automation Testing

A Beginner's Guide to ETL Testing: What You Need to Know