Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How does Selenium perform mouse hover over an element?
Next article icon

How to Handle Alert in Selenium using Java?

Last Updated : 06 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Imagine filling out a form online and accidentally missing some information. You only know if you made a mistake if the website tells you somehow, like with a pop-up message. This article explains what those pop-up messages are called in Selenium (alerts) and how to deal with them in your automated tests.

Prerequisites

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

Note: 

To Open a Chrome Browser Using Selenium please refer to this article How to Open a Chrome Browser Using Selenium in Java? 

Table of Content

  • What are Alerts in Selenium?
  • Types of Alerts in Selenium
  • How to Handle Alerts in Selenium?
  • Example of Alert Handling Using Selenium
  • What are Popups in Selenium?
  • How to handle popups in Selenium?
  • Handling Web Dialog Box/Popup Window using Selenium
  • Conclusion

What are Alerts in Selenium?

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.

Types of Alerts in Selenium

There are three types of Alert in Selenium, described as follows:

  1. Simple Alert
  2. Prompt Alert
  3. Confirmation Alert

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.

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

How to Handle 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"); 

Example of Alert Handling Using Selenium

  1. Launch the web browser and open the webpage “https://demoqa.com/alerts“
  2. Click on the confirmation alert button
  3. Accept the alert
  4. Click on the confirmation alert button again
  5. Reject the alert

Selenium test Script to Handle Alerts:

Java
package GFG_Maven.GFG_MAven;  import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.chrome.ChromeDriver;  public class Geeks {     public static void main(String args[]) throws InterruptedException {                System.setProperty("webdriver.chrome.driver","C:\\Users\\ADMIN\\Documents\\chromedriver.exe");         ChromeDriver driver = new ChromeDriver();                    // Maximize the browser         driver.manage().window().maximize();            // Launch Website         driver.get("https://demoqa.com/alerts");                // clicking on prompt button         driver.findElement(By.xpath("//*[@id=\"confirmButton\"]")).click();         Thread.sleep(3000);                // accepting javascript alert         Alert alert = driver.switchTo().alert();         alert.accept();                  // clicking on prompt button         driver.findElement(By.xpath("//*[@id=\"confirmButton\"]")).click();         Thread.sleep(3000);                // Rejecting javascript alert         Alert alert1 = driver.switchTo().alert();         alert1.dismiss();                      }  } 

Output:

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.

What are Popups in Selenium?

Selenium enables you to handle various types of popups and alerts that may appear during automated browsing, such as JavaScript alerts, modal dialogs, and browser notifications. You can switch to and interact with popup windows or accept/dismiss alerts using appropriate WebDriver methods.

How to Handle Popups in Selenium?

1. Switch to the Alert

Use driver.switchTo().alert(). This tells Selenium to focus on the alert instead of the main page.

2. Interact with the Alert

  1. Get the text: Use alert.getText() to read the message displayed in the alert.
  2. Accept the alert: Use alert.accept() to click the “OK” button (or equivalent).
  3. Dismiss the alert: Use alert.dismiss() to click the “Cancel” button (or equivalent).
  4. Enter text (for prompts): Use alert.sendKeys("text") to input text in prompts before accepting or dismissing.

Example:

Java
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.Alert; import org.openqa.selenium.By;  public class AlertHandlingDemo {      public static void main(String[] args) {         // Set the path to the ChromeDriver executable         System.setProperty("webdriver.chrome.driver", "D:\\driver\\Feb\\chromedriver.exe");//path will be changes as per your chrome browser saved where          // Initialize ChromeDriver         WebDriver driver = new ChromeDriver();          // Navigate to the demoqa alerts page         driver.get("https://demoqa.com/alerts");          // Click the button that triggers an alert         driver.findElement(By.id("alertButton")).click();          // Switch to the alert         Alert alert = driver.switchTo().alert();          // Get and print the alert text         String alertText = alert.getText();         System.out.println("Alert text: " + alertText);          // Accept the alert after getting the alert text         alert.accept();          // Close the browser         driver.quit();     } } 

Handling Web Dialog Box/Popup Window using Selenium

1. Navigate to the webpage “https://demoqa.com/alerts“.

2. Locate and click the button that triggers the alert dialog.

3. Wait for the alert to be present using WebDriverWait.

4. Switch to the alert and print its text.

5. Accept the alert (click OK).

6. Close the browser.

Java
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait;  public class HandleWebDialogBox {     public static void main(String[] args) {         // Set the path to the ChromeDriver executable.         System.setProperty("webdriver.chrome.driver", "D:\\driver\\Feb\\chromedriver.exe");          // Initialize ChromeDriver.         WebDriver driver = new ChromeDriver();          // Navigate to the website.         driver.get("https://demoqa.com/alerts");          // Find and click the "Click me" button to trigger the dialog box.         WebElement clickMeButton = driver.findElement(By.id("alertButton"));         clickMeButton.click();          // Explicitly wait for the alert to be present.         WebDriverWait wait = new WebDriverWait(driver, 10);         wait.until(ExpectedConditions.alertIsPresent());          // Switch to the alert.         org.openqa.selenium.Alert alert = driver.switchTo().alert();          // Get the text from the alert and print it.         System.out.println("Alert Text: " + alert.getText());          // Accept the alert (clicking OK).         alert.accept();          // Close the browser.         driver.quit();     } } 

Conclusion

This article taught us how to deal with alerts and pop-ups when running automated tests using Selenium. Alerts are those small message boxes that show up on the screen and can be either for giving information or asking for user input. We learned different ways to handle these alerts, like accepting them, dismissing them, getting their text, and sending keys to them. Also, we explored how Selenium helps us manage different types of pop-ups and alerts that might come up during automated browsing. The main idea is that knowing how to handle alerts and pop-ups is crucial for making our automated tests strong and reliable.



Next Article
How does Selenium perform mouse hover over an element?

A

allwink45
Improve
Article Tags :
  • Java
  • Selenium
  • Software Testing
  • selenium
Practice Tags :
  • Java

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.
    10 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
    In today's fast-paced software development landscape, integrating automation into development and testing processes is crucial for staying competitive. Automation testing offers numerous benefits, including cost savings, faster feedback loops, better resource allocation, higher accuracy, increased t
    4 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences