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
  • DSA
  • Practice Problems
  • Python
  • C
  • C++
  • Java
  • Courses
  • Machine Learning
  • DevOps
  • Web Development
  • System Design
  • Aptitude
  • Projects
Open In App
Next Article:
How to submit a form in java Selenium webdriver if submit button can't be identified?
Next article icon

How to get text from the alert box in java Selenium Webdriver?

Last Updated : 01 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Automation testing, we can capture the text from the alert message in Selenium WebDriver with the help of the Alert interface. By default, the webdriver object has control over the main page, once an alert pop-up gets generated, we have to shift the WebDriver focus from the main page to the alert with the help of switchTO( ).alert( ) method. Once the driver focus is shifted, we can obtain the text of the pop-up with the help of the technique switchTo( ).getText ( ).

Example to get text from the alert box in Java Selenium Webdriver

Take an example of the alert below and its message.

js1
Site URL

Syntax

Alert al = driver.switchTo().alert();
String st= driver.switchTo().alert().getText();
al.accept();

Here is the code to get text from the alert box in java Selenium Webdriver:

AlertMessage.java
package seleniumpractice;  import java.util.concurrent.TimeUnit; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver;  public class AlertMessage {      public static void main(String[] args) throws Exception     {          System.setProperty(             "webdriver.chrome.driver",             "F:\\ Maven Selenium\\selenium\\src\\main\\java\\seleniumpractice\\chromedriver.exe"); // Replace the Path in which your Chrome Webdriver stay         WebDriver driver = new ChromeDriver();         // implicit wait         driver.manage().timeouts().implicitlyWait(             5, TimeUnit.SECONDS);         // URL launch         driver.get(             "https://the-internet.herokuapp.com/javascript_alerts"); // Replace the Site As per need         Thread.sleep(1000);         // identify element         WebElement we = driver.findElement(By.xpath(             "//*[text()='Click for JS Alert']")); // Location                                                   // of the                                                   // AlertBox         we.click();          // switch focus to alert         Thread.sleep(1000);         Alert al = driver.switchTo().alert();         // get alert text         String st = driver.switchTo().alert().getText();         System.out.println("Alert text is: " + st);         // accepting alert         al.accept();         driver.quit();     } } 

Explanation

Set Up ChromeDriver:

  • System.setProperty() sets the path for ChromeDriver.
  • WebDriver driver = new ChromeDriver(); initializes the browser.
  • Implicit Wait: driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); waits for elements for up to 5 seconds.
  • Open URL: driver.get("https://the-internet.herokuapp.com/javascript_alerts"); navigates to the page with JS alerts.
  • Locate and Click Element: Finds the element triggering the alert using XPath and clicks it.
  • Handle JavaScript Alert:
    • driver.switchTo().alert() switches to the alert.
    • getText() retrieves the alert message.
    • accept() clicks the "OK" button on the alert.
  • Close Browser:
    • driver.quit() closes the browser and ends the WebDriver session.

The script demonstrates handling JavaScript alerts in Selenium with key actions: launching the browser, clicking an element to trigger the alert, and interacting with it.

Output

How to get text from the alert box in java Selenium Webdriver?
Output

Conclusion

Capturing the text from an alert message in Java Selenium WebDriver is a key functionality when automating tests for applications using JavaScript alerts. By accessing the alert using the switchTo().alert() method and retrieving the text with getText(), testers can easily verify the alert content. Implementing this approach ensures more comprehensive test coverage and helps maintain the reliability of web application tests.


Next Article
How to submit a form in java Selenium webdriver if submit button can't be identified?

S

sunilcjd8i
Improve
Article Tags :
  • Selenium

Similar Reads

  • How to upload a file in Selenium java with no text box?
    Uploading a file in Selenium Java without a visible text box can be easily handled using the sendKeys() method. Even if the file input field is hidden or styled as a button, Selenium allows you to interact with it by providing the file path directly. This method simplifies the process of file upload
    3 min read
  • How to check that the element is clickable or not in Java Selenium WebDriver?
    Ensuring that an element is clickable in your Selenium WebDriver tests is crucial for validating the functionality and user experience of your web applications. In Java Selenium WebDriver, checking if an element is clickable before interacting with it can help avoid errors and ensure that your test
    3 min read
  • How to ask the Selenium-WebDriver to wait for few seconds in Java?
    An open-source framework that is used for automating or testing web applications is known as Selenium. There are some circumstances when the particular component takes some time to load or we want a particular webpage to be opened for much more duration, in that case, we ask the Selenium web driver
    9 min read
  • How to Drag and Drop an Element using Selenium WebDriver in Java?
    Selenium is an open-source web automation tool that supports many user actions to perform in the web browser. Automating a modern web page that has a drag and drop functionality and drag and drop is used to upload the files and so many user activities. so to perform the drag and drop actions the sel
    2 min read
  • How to submit a form in java Selenium webdriver if submit button can't be identified?
    Submitting a form in Selenium WebDriver can sometimes be challenging, especially when the submit button cannot be easily identified. In such cases, Java Selenium WebDriver offers alternative methods to interact with web elements and successfully submit the form. Whether the submit button lacks a uni
    3 min read
  • How to mute all sounds in chrome webdriver with selenium using Java?
    In some automated testing situations, the website may play audio or video. This may interfere with the test operation. To solve this problem, turning off all sounds in Chrome during Selenium WebDriver testing ensures a quieter environment. It improves the efficiency and accuracy of test results. Thi
    3 min read
  • How to do session handling in Selenium Webdriver using Java?
    In Selenium WebDriver, managing browser sessions is crucial for ensuring that each test runs independently and without interference. A browser session in Selenium is identified by a unique session ID, which helps track and manage the session throughout the test. Proper session handling in Selenium W
    4 min read
  • How to Handle Alert in Selenium using Java?
    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
    6 min read
  • How to Take a Screenshot in Selenium WebDriver Using Java?
    Selenium WebDriver is a collection of open-source APIs used to automate a web application's testing. To capture a screenshot in Selenium, one must utilize the Takes Screenshot method. This notifies WebDriver that it should take a screenshot in Selenium and store it. Selenium WebDriver tool is used t
    3 min read
  • How to Handle iframe in Selenium with Java?
    In this article, we are going to discuss how to handle the iframe in Selenium with Java. The following 6 points will be discussed. Table of Content What are iframes in Selenium?Difference between frame and iframe in SeleniumSteps to Identify a Frame on a Page?How to Switch Over the Elements in ifram
    11 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