Alerts in Selenium

Alerts on the webpage used to get the attention of the user to perform some operation on the alert or the webpage; sometimes, the alert expects input from the user. All the alerts are formed using javascript inside the HTML page; there are three kinds of alerts in HTML.

Alert takes the focus away from the current window and forces the browser to read the message. Alert prevents the user from accessing other parts of the web page until the box is closed.

Alert Types :

  • Alert
  • Confirmation dialog
  • Prompt

Properties of Alerts with respect to Selenium :

  • We cannot identify alerts using inspect tools
  • We cannot write xpaths for alerts
  • It is not a Window
  • We cannot handle alerts using javaScript Executor

We can consider not alert if any of the above property mismatches.

Code of Alert handling in selenium

When an alert is present on the webpage, we cannot proceed further without handling the popup, and if we try to perform any operation throws UnhandledAlertException.

We can handle alerts using switchTo().alert() method present in selenium, with the help of this alert() we can handle the popup.

Syntax to handle popup

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

Technical Tip : Selenium up-cast the object to Alert Interface in the above line of code With this API, we can perform the below operations on the pop-up.

1. Accept the popUp by clicking the OK button


2. Dismiss the popUp by clicking the 'X' icon.


3. Get popUp text by getText method


4. Send a text to popUp by sendKeys (Applicable for Prompt only)

ale.sendKeys("test Text");
Webdriver never clicks the Cancel button on any kind of alert

When do alerts occur on a page: It can occur on a page at any time, but most of it happens on below timing of the webpage

  • On Webpage Load
  • On Webpage close
  • On click of an element
  • On Right-click (when right-clicking disabled)
  • On wrong entry of a field
  • On information save
Technical Tip : Now day developer are using overlays/hidden division popups rather than javascript popups

Learn about Constructors in selenium and Java


The alert() method displays an alert box with a message and an OK button; an alert box is often used to inform a user about a particular operation like details saved in Database, right-click disabled, Loaded successfully such kind of messages.

Alert is formed using alert("message") in javascript, alert considers the same irrespective of user operation whether he clicks OK or 'X' icon.

Alert's sole purpose is to inform the user, nothing more.

Alert on Different browsers


    • Open Url :
    • Click on the Alert button; the application throws an Alert box
    • Switch to the alert using driver.switchTo().alert(), we save this object in Alert type variable 'ale'
    • We can accept the alert by using accept() non-static method from the alert API, and this closes the popup.
Alert ale = driver.switchTo().alert();
// clicks 'OK' button
    • We can dismiss the popup using dismiss() method from alert API, this click 'X' icon on the popup. (if you have performed the above step then you cannot perform this step as pop up is closed in step 4 itself)
Alert ale = driver.switchTo().alert();
// clicks 'x' icon
    • We can get the text from the pop-up using getText(), if you have performed steps 4 or 5, this step will not work.
Alert ale = driver.switchTo().alert();
// clicks 'x' icon


Handle dropdowns in selenium

Confirmation Box

A Confirmation box is the second kind of alert; it displays a dialog with the OK and Cancel button. The confirmation box informs the developer about user choice whether the user pressed OK or Cancel. The confirm() method returns true if the user clicked "OK", and false otherwise('X' icon and 'Cancel') to the developer.

Confirmation box confirm-chrome-selenium-webdriver

We can handle the Confirmation box in selenium like an alert box; there is no coding difference.

Learn about NoAlertPresentException in Webdriver


Prompt is used to get value from the user in text format. Prompt provides a text bar for user input; Prompt is rarely used alert type.

Prompt also follows the same coding as alert and prompt except the sendkeys method, and we can send a text to prompt text bar using the sendkeys() method in alerts API.

You cannot use the Keys.ENTER or such kind of keys with sendkeys() method of alerts
Alert ale = driver.switchTo().alert();

Handling nested frames in Selenium

How to check whether the alert is present or Not?

We can use Explicit wait / WebdriverWait to check whether the alert is there or not, alertIsPresent() method waits for the alert to be present till the given timeout, once it reaches a timeout, and if the alert is not present, then it throws TimeOutException if the alert is present before the timeout it proceeds with remaining code.

I have used only 2 seconds to check for the alert.

public static boolean isAlertPresent(){
    boolean presenceOfAlert = false;
    WebDriverWait wait = new WebDriverWait(driver, 2 /*timeout in seconds*/);
    try {
        presenceOfAlert = true;
    } catch (TimeoutException e) {
        presenceOfAlert = false;
    return foundAlert;

Explanation :

  • We are setting presenceOfAlert to false; this is for by default value.
  • We are creating an object for WebdriverWait
  • We are using try{} block to see whether the code throws an exception or not
  • We are checking whether the alert is there or not using alertIsPresent() method. If an alert is present, then execution goes to the next line where we have set presenceOfAlert to true, but in case if the alert is not there, it will not execute "presenceOfAlert = true;" statement but goes to catch block.
  • We have used catch{} block to receive the exception, this catch block receives only TimeoutException
  • If try block code throws TimeoutException then presenceOfAlert = false; will be executed
  • The method returns the value based on the try-catch block / based on the presence of an alert.

Get text from an element in Selenium

Screenshot of an Alert

Taking a screenshot without handling an alert is not possible, but you can take a screenshot using the robot class or any other external class present in java.

What you cannot do is, you cannot use the driver instance for any operation without handling the alert.

Actually, the below code copies the screenshot to the clipboard.

// Press the key combination of (Windows + PrintScreen) by using Robot Class
Robot rb = new Robot();

So using the screenshot method in selenium, we cannot capture the screenshot of javascript alert

Take Page & Element Screenshot, Compare Screenshots in selenium

About Author :

I am Pavankumar, Having 8.5 years of experience currently working in Video/Live Analytics project.

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
  • Jonathan
    Great tutorial!
    Is it possible to wait for user input to the prompt (but without using Threads.sleep..) ?
    I mean something like this:
    js.executeScript("window.promptResponse=prompt('Enter something')");
    *here, wait for the user to input or just wait for prompt to close (same idea)
    thank you!
  • chandrasekhar
    In How to check whether the alert is present or Not ? section,
    return foundAlert;
    Where you declared foundAlert ??
    • Admin
      My bad, it should be presenceOfAlert
  • Great Tutorial
  • Snehal
    Very useful blog...Thank you very much.
    • Author
      Great, Snehal
  • poorna pragna
    Excellent one! most of the points are covered. This very useful at the time interview.
    Poorna Pragna
  • kauser
    very good blog...pretty detailed..please launch a telegram or whatsapp group technical discussions..
    • karthiq [admin]
      Thanks for you Feedback,
      We will create a group [ I donot even know, what is telegram :p ],
      but we will do