Pop Ups in Selenium

How To Handle Javascript Alerts/PopUps In Selenium WebDriver:

In this post, we see how to handle javascript alerts/popus. Alerts are basically popup boxes that take your focus away from the current browser and forces you to read the alert message. You need to do some action such as accept or dismiss the alert box to resume your task on the browser.

To handle alerts popupswe need to do switch to the alert window and call Selenium WebDriver Alert API methods.

There are two types of alerts.

  1. Windows Based
  2. Web Based/Browser Based

Here in this post, I confine to Java Script Alerts (A.K.A. Browser/Web Based Alerts).

To handle Browser based Alerts (Web based alert popups), we use Alert Interface. The Alert Interface provides some methods to handle the popups.

While running the WebDriver script, the driver control will be on the browser even after the alert generated which means the driver control will be behind the alert pop up. In order to switch the control to alert pop up, we use the following command :

driver.switchTo().alert();

Once we switch the control from browser to the alert window. We can use the AlertInterface methods to do required actions such as accepting the alert, dismissing the alert, get the text from the alert window, writing some text on the alert window etc.,

Let’s see the Alert Interface Methods.

We need to Import a package org.openqa.selenium.Alert to handle the alerts in Selenium.

To get a handle to the open alert:

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

To Click on OK button:

alert.accept();

To click on Cancel button.

alert.dismiss()

To get the text which is present on the Alert.

alert.getText();

To enter the text into the alert box

alert.sendkeys(String stringToSend);

Sample Program:

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class AlertPopup {

	public static void main(String[] args) throws InterruptedException {
		WebDriver driver = new FirefoxDriver();
		driver.manage().window().maximize();
		driver.get("http://www.testingbar.com/alert-popup/");
		driver.findElement(By.xpath("//*[@id='post-1136']/div/p[3]/button")).click();

		Alert a1 = driver.switchTo().alert();
		System.out.println(a1.getText()); //To get the text which is present on the Alert.
		Thread.sleep(5000);
		a1.accept(); //Click on OK
		driver.findElement(By.xpath("//*[@id='post-1136']/div/p[3]/button")).click();
		Thread.sleep(5000);
		a1.dismiss(); //Click on Cancel
	}
}

Leave a Reply

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