Skip to content
Related Articles
Open in App
Not now

Related Articles

How to Handle Alert in Selenium using Java?

Improve Article
Save Article
Like Article
  • Last Updated : 11 Apr, 2022
Improve Article
Save Article
Like Article

An alert is nothing but a small message box that appears on the screen to give some kind of information or give a warning for a potentially damaging operation or it asks permission for performing that operation.

Types of Alerts

1. Simple Alert

The simple alert in selenium shows some information or warning on the window.

Simple Alert


2. Confirmation Alert

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

Confirmation alert


3. Prompt Alert

Prompt Alert asks some input from the user.

Prompt Alert


Handling Alert 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.


2. void accept() 

The void accept method is used to click on the ‘OK’ button of the alert.


3. String getText() 

The void accept method is used to capture the alert message..


4. void sendKeys(String stringToSend)

It is used to send some data to the prompt alert.


Scenario to be Automated

  • Launch the web browser and open the webpage “
  • Click on the confirmation alert button
  • Accept the alert
  • Click on the confirmation alert button again
  • Reject the alert


  • Eclipse IDE:  Before downloading also make sure that your device has Java JDK. If you don’t have, to install Java refers to this: How to Download and Install Java for 64 bit machine?. And install Eclipse IDE by referring to this article Eclipse IDE for Java Developers
  • Selenium: Download the Selenium latest stable version here
  • Web Driver: Download the Microsoft Edge Webdriver according to your version here 

Note:  To open Chrome Browser Using Selenium please refer to this article How to Open Chrome Browser Using Selenium in Java? 



package GFG_Maven.GFG_MAven;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
public class Geeks {
    public static void main(String args[]) throws InterruptedException {
        ChromeDriver driver = new ChromeDriver();
        // Maximize the browser
        // Launch Website
        // clicking on prompt button
        // accepting javascript alert
        Alert alert = driver.switchTo().alert();
        // clicking on prompt button
        // Rejecting javascript alert
        Alert alert1 = driver.switchTo().alert();


The program will open the website and click on the confirmation alert button and accept the alert and again it click the alert button and decline the alert.



My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!