How to Handle Alerts and Popups in Selenium

Handling alerts and popups is an essential part of web automation with Selenium WebDriver. In this blog, we’ll cover everything you need to know about How to Handle Alerts and Popups in Selenium, including their types, how to interact with them, common issues, and practical programmatical examples.

Whether you’re a beginner or an experienced web automation tester, this blog will help you improve your skills and create more robust and reliable automated tests.

Alerts in Selenium WebDriver

Alerts in Selenium WebDriver are dialog boxes that can appear during the execution of a test script. These alerts can provide important messages or require user input before the test can proceed

Types of Alerts and How to Handle Them in Selenium

Selenium supports three types of alerts: simple alerts, confirmation alerts, and prompt alerts. Here’s how you can handle each type of alert using the “Alert” interface in Selenium.

  • Simple Alerts:
    Simple alerts have only one button, which is the “OK” button. To handle a simple alert, you can use the following Syntax:
Alert simpleAlert = driver.switchTo().alert();
String alertText = simpleAlert.getText();
System.out.println("Alert text is " + alertText);
simpleAlert.accept();
  • Confirmation Alerts:
    Confirmation alerts have two buttons: “OK” and “Cancel”. To handle a confirmation alert, you can use the following Syntax:
Alert confirmationAlert = driver.switchTo().alert();
String alertText = confirmationAlert.getText();
System.out.println("Alert text is " + alertText);
//For ok
confirmationAlert.accept();
//For cancel
confirmationAlert.dismiss();
  • Prompt Alerts:
    Prompt alerts are similar to confirmation alerts, but they also have an input field where the user can enter text. To handle a prompt alert, you can use the following Syntax:
Alert promptAlert = driver.switchTo().alert();
String alertText = promptAlert.getText();
System.out.println("Alert text is " + alertText);
promptAlert.sendKeys("Selenium 4 is awesome!");
promptAlert.accept();

Practical Demonstration on How to Handle Alerts in Selenium

We have used https://the-internet.herokuapp.com/javascript_alerts for practical demonstration:

import java.time.Duration;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class AlertExample {
	public static void main(String[] args) {

		// Launch the browser
		WebDriver driver = new ChromeDriver();

		// Navigate to the website
		driver.get("https://the-internet.herokuapp.com/javascript_alerts");
		driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));

		// 1. Simple Alerts:
		// Click the "Click for JS Alert" button
		WebElement alertButton = driver.findElement(By.cssSelector("button[onclick='jsAlert()']"));
		alertButton.click();

		// Switch to the alert dialog
		Alert simplealert = driver.switchTo().alert();

		// Get the text of the alert message
		String alertMessage = simplealert.getText();
		System.out.println("Alert message: " + alertMessage);

		// Click the "OK" button to close the alert
		simplealert.accept();

		// Print the result
		String Result = driver.findElement(By.xpath("//p[@id='result']")).getText();
		System.out.println(Result);

		// 2. Confirmation Alerts:
		// Click the "Click for JS Confirm" button
		WebElement ConfirmButton = driver.findElement(By.cssSelector("button[onclick='jsConfirm()']"));
		ConfirmButton.click();

		// Switch to the alert dialog
		Alert confirmalert = driver.switchTo().alert();

		// Get the text of the alert message
		alertMessage = confirmalert.getText();
		System.out.println("Alert message: " + alertMessage);

		// Click the "cancel" button to cancel the action
		confirmalert.dismiss();

		// Print the result
		Result = driver.findElement(By.xpath("//p[@id='result']")).getText();
		System.out.println(Result);

		// 3. Prompt Alerts:
       // Click the "Click for JS Prompt" button
		WebElement PromptButton = driver.findElement(By.cssSelector("button[onclick='jsPrompt()']"));
		PromptButton.click();

		// Switch to the alert dialog
		Alert promptalert = driver.switchTo().alert();

		// Get the text of the alert message
		alertMessage = promptalert.getText();
		System.out.println("Alert message: " + alertMessage);

		// Enter the value into input field
		promptalert.sendKeys("TestingMint Is Best Software Testing Blog");

		// Click the "OK" button to accept the action
		promptalert.accept();

		// Print the result
		Result = driver.findElement(By.xpath("//p[@id='result']")).getText();
		System.out.println(Result);

		// Close the browser
		driver.quit();
	}
}

Output:

Popups in Selenium WebDriver

Popup refers to a browser window that appears on top of the existing browser window, typically in response to a user action or some event triggered by the web application being tested. Popups can come in various forms, including alerts, confirmation messages, prompts, and modal dialogs.

How to handle popups in Selenium

To handle Popups in Selenium WebDriver, the following methods can be used:

  • getWindowHandle():
    This method returns the unique string handle of the current window or tab. This method is used to switch to a specific window or tab in a multi-window or multi-tab scenario. The window handle is a unique identifier for the browser window, which is generated by the browser.
    Syntax:
// Switch to the new window
for (String handle : driver.getWindowHandles()) {
    driver.switchTo().window(handle);
}
  • getWindowHandles():
    This method returns a set of string handles for all the windows or tabs currently open in the browser. This method is used when there are multiple windows or tabs open in the same browser session.
    Syntax:
// Get the number of open windows
int windowCount = driver.getWindowHandles().size();

// Print the window count to the console
System.out.println("Number of open windows: " + windowCount);

Practical Demonstration on How to Handle Popups in Selenium

We have used https://demo.guru99.com/popup.php for practical demonstration:

First Window
Second Window
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class PopupExample {
	public static void main(String[] args) {

		// Launch the browser
		WebDriver driver = new ChromeDriver();
		driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));

		// Navigate to the website
		driver.get("https://demo.guru99.com/popup.php");

		// Find the link to the popup window and click it
		WebElement popupLink = driver.findElement(By.linkText("Click Here"));
		popupLink.click();

		// Get the window handles of the current page
		String mainWindowHandle = driver.getWindowHandle();
		String popupWindowHandle = null;
		for (String handle : driver.getWindowHandles()) {
			if (!handle.equals(mainWindowHandle)) {
				popupWindowHandle = handle;
				break;
			}
		}

		// Switch to the popup window and perform actions on it
		driver.switchTo().window(popupWindowHandle);
		WebElement emailInput = driver.findElement(By.name("emailid"));
		emailInput.sendKeys("info@testingmint.com");
		WebElement submitButton = driver.findElement(By.name("btnLogin"));
		submitButton.click();

		// Switch back to the main window and close the browser
		driver.switchTo().window(mainWindowHandle);

		// Print the window count
		int windowCount = driver.getWindowHandles().size();
		System.out.println("Number of open windows: " + windowCount);
	}
}

Common Issues and How to Resolve Them

When working with alerts and popups in Selenium WebDriver, there can be some common issues that you may encounter. Here are a few common issues and their possible solutions:

  • NoAlertPresentException:
    This exception is thrown when there is no alert present on the page, and you try to switch to an alert. To resolve this issue, you can add a wait before switching to the alert, to give it time to appear on the page.
    Syntax:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.alertIsPresent());
  • UnhandledAlertException:
    This exception is thrown when you try to interact with an element on the page while an alert is still open. To resolve this issue, you can first switch to the alert and either accept or dismiss it before interacting with the element.
    Syntax:
Alert alert = driver.switchTo().alert();
alert.accept();
  • Popup window not opening:
    If a popup window is not opening, it could be due to an incorrect locator or an issue with the popup window itself. You can try using a different locator, or check the popup window code to ensure it is functioning correctly.
  • Multiple windows or tabs open:
    If there are multiple windows or tabs open in the browser, it can be difficult to determine which window or tab to switch to. In this case, you can use the getWindowHandles() method to get a set of handles for all the open windows, and then use the switchTo().window() method to switch to a specific window.
    Syntax:
Set<String> windowHandles = driver.getWindowHandles();
for (String windowHandle : windowHandles) {
    driver.switchTo().window(windowHandle);
}

Conclusion

In conclusion, handling alerts and popups in Selenium WebDriver can be a crucial part of web automation. Alerts and popups are commonly used in web applications to provide important information or to prompt the user to take a specific action. In order to handle these alerts and popups, it is important to understand their types and how to interact with them using Selenium WebDriver.

Overall, understanding how to handle alerts and popups in Selenium WebDriver can be extremely beneficial for web automation, and can help to ensure that your automated tests are robust and reliable.

FAQ

What is the difference between an alert and a popup in Selenium WebDriver?

An alert is a message that appears on the screen to notify the user of an event or to prompt them to take a specific action. A popup, on the other hand, is a window that opens on top of the main browser window, usually containing additional information or a form to fill out.

How do I switch to an alert in Selenium WebDriver?

To switch to an alert, you can use the switchTo().alert() method in Selenium WebDriver. This method allows you to interact with the alert and accept or dismiss it.

How do I handle a popup window in Selenium WebDriver?

To handle a pop-p window, you can use the switchTo().window() method in Selenium WebDriver to switch to the popup window. Once you have switched to the window, you can interact with its elements as you would with any other web page

You Might Like: