How to handle alerts in Selenium WebDriver

By | August 9, 2020

How to handle alerts in Selenium WebDriver:

Selenium WebDriver is able to handle alerts in addition to the windows and frames. This tutorial explains how to handle alerts in selenium.

Alerts in selenium:

What is an alert?

Alert is a popup or message box which displays on the screen. Alerts can appear on the screen due to various user actions. For example, alert can appear when you click on a button or trying to navigate to other page.

selenium alert handling



Alert alert;

Alert is an interface which has below methods to execute different actions.

void accept() – It is similar to the Ok button. It clicks on the Ok button on the alert box.

void dismiss() – It is similar to the Cancel button.

void sendKeys() – It send the text on to the alert box.

getText() – It retrieves the text from the alert box. Used to evaluate the text present on the prompt or alert boxes.

Types of Alerts:

  1. Simple alert: It just have an Ok button in it. It is an informative kind of alert.
  2. Prompt alert: This alert asks the user for some information. User can enter the information into this alert using sendKeys() method.
  3. Confirmation alert: This type of alert asks for the user confirmation whether to proceed or not. For instance, when you are trying to delete a file, you may encounter this tyepe of alert.


How to handle alerts in Selenium WebDriver:



Output on the Console:

Hello! This is an alert box.
PASSED: alertMethod

You can try this yourself by following below steps:

1. Open Notepad.

2. Copy and paste below code.

<!DOCTYPE html>

<h2>Click the button to display an alert box/confirm popup.</h2>
<p><b>Alert box:</b></p>
<button id=”alert_id1” onclick=”myFunction1()”>Click here</button>
<br />
<p><b>Confirm popup:</b></p>
<button id=”alert_id2” onclick=”myFunction2()”>Submit</button>
<br />
<p id=”demo”></p>
<p><b>Prompt dialog:</b></p>
<button id=”alert_id3” onclick=”myFunction3()”>Enter</button>
function myFunction1() {
alert(“Hello! This is an alert box.”);

function myFunction2() {
confirm(“Hello! This is a confirm popup.”);

function myFunction3() {
var name = prompt(“Please enter your name”, “Selenium user”);
if (name != null) {
document.getElementById(“demo”).innerHTML = “Hello ” + name + “! Have a great day.”;


3. Save file with .html extension.

4. Change the file path in selenium code and run the script.

Check other selenium topics:

How to handle mouse hover events using Selenium WebDriver

WebElement actions in selenium WebDriver

Top 25 selenium interview questions

How to take screenshot using Selenium WebDriver

StringUtils equalsAny() method

StringUtils trim() method

StringUtils methods in real-time

Tags: Selenium handle alerts. Handle alerts using selenium web driver, Handle alerts in Selenium WebDriver.

Leave a Reply

Your email address will not be published. Required fields are marked *