How to Handle Alert in Selenium using Java?
Last Updated :
28 Jul, 2025
In Selenium WebDriver, handling alerts is a common requirement for automating interactions with web applications. An Alert is nothing but a small message box that appears on the screen to give some kind of information and give a warning for a potentially damaging operation or permission to perform that operation.
These alerts classified into three types:
- Simple Alert
- Prompt Alert
- Confirmation Alert
1. Simple Alert
The simple alert in selenium shows some information or warning on the window.

2. Confirmation Alert
The confirmation alert asks for the permission to do some type of operations.

3. Prompt Alert
Prompt Alert asks some input from the user.

Methods of Handing Alerts in Selenium
There are the four methods that we would be using along with the Alert interface.
1. void dismiss()
The void dismiss method is used to click on the ‘Cancel’ button of the alert.
Java
driver.switchTo().alert().dismiss();
2. void accept()
The void accept method is used to click on the ‘OK' button of the alert.
Java
driver.switchTo().alert().accept();
3. String getText()
The void accept method is used to capture the alert message..
Java
driver.switchTo().alert().getText();
4. void sendKeys(String stringToSend)
It is used to send some data to the prompt alert.
Java
driver.switchTo().alert().sendKeys("Text");
Prerequisites
Before Handling alerts please download and make sure you have setup the below dependency for the automation of alerts.
- Java JDK, If you don’t have, to install Java refer to this: Download & Install Java.
- Install Eclipse IDE by referring to this article: Install Eclipse.
- Download the latest stable version of Selenium: Selenium Official Download Page.
- Download the Chrome WebDriver according to your version Here.
- Before handling alerts, you have to learn first to Open Chrome Browser Using Selenium.
Example of Alert Handling Using Selenium
let's first set up a basic Selenium test environment with Java. Below is a basic structure of how to set up a WebDriver instance for running the tests.
BaseTest.java
Java
package io.learn;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
public class BaseTest {
protected WebDriver driver;
// Set up the ChromeDriver
@BeforeMethod
public void setup() {
// Set the path to your chromedriver executable
System.setProperty("webdriver.chrome.driver", "C:\\Users\\path of the chromedriver\\drivers\\chromedriver.exe");
// Initialize the ChromeDriver
driver = new ChromeDriver();
}
// Close the browser after each test
@AfterMethod
public void teardown() {
if (driver != null) {
driver.quit();
}
}
}
In BaseTest setup, the ChromeDriver is initialized, and the WebDriver is configured to open and close the browser automatically for each test.
Create class AlertTest.java
, and combined the three types of alerts:
- Simple Alert: This alert shows a message and has only an "OK" button. We click the button to trigger the alert, then switch to the alert, verify its message, and accept it.
- Confirmation Alert: This alert asks a user to confirm or cancel an action, with "OK" and "Cancel" options. We click the button to open the confirmation alert, verify its message, and dismiss the alert (selecting "Cancel").
- Prompt Alert: This alert asks the user to enter some text. We click the button to open the prompt alert, enter some text in the input field, and accept the alert to submit the text.
AlertTest.java
Java
package io.learn.alerts;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.testng.Assert;
import org.testng.annotations.Test;
import io.learn.BaseTest;
public class AlertTest extends BaseTest {
String URl1 = "https://bonigarcia.dev/selenium-webdriver-java/dialog-boxes.html";
@Test
void testAlert() {
driver.get(URl1);
driver.findElement(By.id("my-alert")).click(); // Triggering simple alert
// Handling the alert
Alert alert = driver.switchTo().alert();
Assert.assertEquals(alert.getText(), "Hello world!");
alert.accept(); // Accept the alert (click OK)
System.out.println("Simple Alert Executed Successfully");
}
@Test
void testConfirm() {
driver.get(URl1);
driver.findElement(By.id("my-confirm")).click(); // Triggering confirmation alert
// Handling the confirmation alert
Alert confirm = driver.switchTo().alert();
Assert.assertEquals(confirm.getText(), "Is this correct?");
confirm.dismiss(); // Dismiss the alert (click Cancel)
System.out.println("Confirmation Alert Executed Successfully");
}
@Test
public void testPromptAlert() {
driver.get(URl1);
driver.findElement(By.id("my-prompt")).click(); // Triggering prompt alert
// Handling the prompt alert
Alert prompt = driver.switchTo().alert();
prompt.sendKeys("vaibhav"); // Enter text in the prompt
prompt.accept(); // Accept the prompt (click OK)
System.out.println("Prompt Alert Executed Successfully");
}
}
Output
Output of Handling AlertsHandling Alert GetText and Validation
In many scenarios, you may need to get the message of an alert to perform some validation. Selenium provides the getText()
method for this purpose.
AlertGetText.java
Java
package io.learn.alerts;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.testng.Assert;
import org.testng.annotations.Test;
import io.learn.BaseTest;
public class AlertGetText extends BaseTest {
@Test
void testConfirm() {
driver.get("https://bonigarcia.dev/selenium-webdriver-java/dialog-boxes.html");
driver.findElement(By.id("my-confirm")).click(); // Clicking the confirmation alert button
// Switch to the confirmation alert
Alert confirm = driver.switchTo().alert();
// Get and validate the text of the alert
Assert.assertEquals(confirm.getText(), "Is this correct?");
System.out.println(confirm.getText());
// Dismiss the alert (clicking "Cancel")
confirm.dismiss();
System.out.println("Confirmation Alert Executed Successfully");
}
}
Output of Get Text in selenium WebDriverHandling alerts is a fundamental skill for any Selenium WebDriver user. Whether it's a simple message alert, a confirmation alert, or a prompt requiring user input, Selenium offers straightforward methods to interact with them effectively in the automation testing.
Similar Reads
Automation Testing - Software Testing Automated Testing means using special software for tasks that people usually do when checking and testing a software product. Nowadays, many software projects use automation testing from start to end, especially in agile and DevOps methods. This means the engineering team runs tests automatically wi
15+ min read
Automation Testing Roadmap: A Complete Guide to Automation Testing [2025] Test automation has become a vital aspect of the Software Development Life Cycle (SDLC), aimed at reducing the need for manual effort in routine and repetitive tasks. Although manual testing is crucial for ensuring the quality of a software product, test automation plays a significant role as well.
9 min read
How to Start Automation Testing from Scratch? Automation Testing is the practice of using automated tools and scripts to execute tests on software applications, reducing manual effort and increasing efficiency. Starting automation testing from scratch involves several key steps, including selecting the right automation tool, identifying test ca
8 min read
Benefits of Automation Testing Automation testing transforms software development by offering significant advantages over manual testing. Below are the 8 Key benefits mentioned in detail:1. Saving CostsAutomated tests can be run concurrently on multiple devices and environments without the need for manual intervention. This reduc
3 min read
Stages of Automation Testing Life Cycle In this article, we will explore the phases and methodologies involved in automation testing and the phases of the automation testing lifecycle. We'll cover everything from scoping your test automation to creating a solid test plan and strategy. You'll also learn about setting up the perfect test en
12 min read
Top Automation Testing Books For 2024 In this article, we can explore the top 10 books for automation testing, providing a top-level view of each book's content material and why it's worth considering for everybody interested in this sector. Table of Content Top 10 Books for Automation Testing BooksConclusionFAQs on Top Automation Test
12 min read
Top Test Automation mistakes and Tips for QA teams to avoid them In the dynamic landscape of software testing, avoiding common test automation pitfalls is crucial for QA teams aiming for efficient and successful testing processes. This article delves into prevalent errors in test automation and provides valuable insights on how QA teams can steer clear of these m
7 min read
Essential Skills for a Successful Automation Tester In the domain of software testing, automation plays a crucial role in ensuring efficiency, accuracy, and speed. However, to be a successful automation tester, one must possess a specific set of skills beyond just technical proficiency. This article explores the essential skills required for automati
6 min read
Steps to Select the Right Test Automation tools Selecting the right test automation tools is critical for ensuring efficient and effective testing processes in software development projects. In this article, we will discuss the key steps involved in choosing the most suitable automation tools for your project needs. From understanding project req
5 min read
Best Test Automation Practices in 2024 Test Automation continues to evolve with new technologies and methodologies emerging each year. In 2024, staying updated with the latest best practices is crucial for efficient and effective testing processes. From robust test design to continuous integration and deployment, this article explores th
7 min read