Selenium WebDriver - Handle Alerts or Pop-Ups

In this post we will learn to handle alerts or popups with Selenium Webdriver using Java. Generally there are two types of alerts:
  1. Web based Alerts
  2. Window alerts
Out of these two only web based alerts can be handled using Selenium Webdriver. Window alerts cannot be handled using selenium webdriver, but there are other ways of handling the window alerts and we will discuss that strategy in next post. In this post we are going to handle web based alerts.

What is a web alert?
A web alert is generally a javascript based pop-up that appears on the screen. It commonly have a text message and two buttons which could be Yes or No, Accept or Dismiss, Ok or Cancel.

So there aren't much operations we can perform on an alert. Below are the commands used to handle web alerts:
  1. alert.accept()
  2. alert.dismiss()
  3. alert.getText()

/*  Alert handling   */

// Alert class object creation
Alert alert = driver.switchTo().alert();

// Below Code switches the control/focus of your execution to the alert

// Below command is used to accept the alert like click on Yes, Accept, Ok button

// Below command is used to dismiss/reject the alert like click on No, Dismiss, Cancel button

Sharing an example below in which, code snippet represents an example to validate Pop-up text.

// Expected Text
String expectedPopUpText = "Congratulations!";

// Expected text - getText() is the command to get text from a pop-up
String actualPopUpText = alert.getText();

// Print pop up text value before validation

// Validate text
if expectedPopUpText == actualPopUpText){
    System.out.println("Pop Up Text matched.");
    System.out.println("Pop Up Text does not matched.");

Thanks for reading, share your thoughts in comments. Happy Learning! :)

For list of  Selenium tutorials click here: Selenium Webdriver Tutorials Series
Author: Vaneesh Behl
Join Telegram channel of this blog at


  1. Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care.As always, we appreciate you confidence and trust in us. selenium online training


Post a Comment

Popular Posts

Top 10 Demo Websites to Practice Selenium Webdriver Online

REST API Tutorial - Manual Testing of APIs using Postman

REST API Automation Tutorial using Postman

Selenium WebDriver - Browser and Navigation Commands

Top 20 Advanced Selenium Webdriver Coding Interview Questions of 2019