Handling Alert dialog, Popup windows and Frames | Handling Alert dialog

In this tutorial, we will learn how to handle Alert windows using the Alerts interface provided by WebDriver.

3 min read

In the Previous Tutorial, we learned how to handle timeout issues in Selenium. In this tutorial, we will learn how to handle Alert windows.

You must have noticed that on clicking some links/buttons, the page displays an alert window that asks the user to confirm if she or he wants to do this action by clicking on OK/Cancel or Yes/No buttons. Some of them display text like this – "Are you sure you want to perform this action?". You can check it out yourself by going to the Automation Practice page. When you'll click on the link – 'Click Me to get Alert', the page will prompt this alert:

This popup window is not part of the web page so normal Selenium code won't be able to perform any action on it. It is a JavaScript Alert window. To handle these type of scenarios WebDriver has given Alerts interface.

System.setProperty("webdriver.chrome.driver", "C:\\teachmeselenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://cosmocode.io/automation-practice");
driver.findElement(By.linkText("Click Me to get Alert")).click();

As this statement is executed, the browser will prompt an alert as displayed in the above screenshot. To perform any action on this alert window, WebDriver first, needs to switch to it.

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

You need to import package org.openqa.selenium.Alert for the Alert interface.

Now we have an Alert object, we can perform actions on it.

String strAlertText = alert.getText();

When we type alert followed by a dot(.), your code editor will suggest some more options. Try it out and let me know your finding in comments.

System.setProperty("webdriver.chrome.driver", "C:\\teachmeselenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://cosmocode.io/automation-practice");
driver.findElement(By.linkText("Click Me to get Alert")).click();
Alert alert = driver.switchTo().alert();
String strAlertText = alert.getText();
System.out.println(strAlertText);
alert.accept();
//alert.dismiss();
driver.quit();
alert.accept();
alert.dismiss();

This tutorial was so short and crispy. Wasn't it? In the Next Tutorial, we will explore real-world challenges like handling popup windows.