Handling Alert/ Popups in Selenium WebDriver with Java

Handling Alerts/ Popups is one of the challenging tasks while automating the web application.

There are mainly two types of Alerts.

  1. Windows based alerts
  2. Web based alerts

As we know already, Selenium is not able to handle Window based alerts, we need to use some third party tools to get our work done.

So, we will be focusing on handling web based alerts here with Selenium WebDriver.

What is Alert?

Alert is just a small box generated by Javascript code on some event performed. It gives the user some information and asks for the permission to proceed its operation further.

Sample alert generated by w3schools.com


Now, in order to handle such alert, WebDriver API comes with special interface Alert.

Alert is an interface provided by WebDriver API and contains 4 main methods.

  1. void dismiss() : Dismisses the alert box (Simulates pressing close button of Alert)
  2. void accept() : Accepts the alert box (Simulates pressing OK button of Alert)
  3. void sendKeys(String str) : Enters value in text field of a prompt box
  4. String getText() : Returns the text of Alert 


Now, we will see how to perform these operation through automation code.

Getting an instance of Alert :


Alert alert = driver.switchTo().alert();

Accepting the Alert : 


Dismissing the Alert : 


Getting text of Alert : 

String alertText = alert.getText();

Entering values in Prompt box’s text field : 


Let’s have a look at below code snippet in action.

import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class AlertDemo {
             public static void main(String[] args) throws Exception {

                          WebDriver driver = new FirefoxDriver();

                          String url = “http://www.web-source.net/web_design_tips/alert_message_web_page_load.htm”;


                           Alert alert = driver.switchTo().alert();
                           System.out.println(“Alert box text ” + alert.getText());

                           System.out.println(“Accepted the alert.”);

                           alert = driver.switchTo().alert();

                           System.out.println(“Alert box text again ” + alert.getText());

                          System.out.println(“Dismissed the alert this time.”);



Hope it helps you !!

Cheers 🙂




#accept-the-alert, #dismiss-the-alert, #get-text-of-alert, #handling-alert-in-selenium-webdriver, #handling-popup-in-selenium