JavaScript alerts are messages that pop up on websites to notify users about something important, ask for confirmation before proceeding, or request input. As a tester who automates tests, it's crucial to know how to deal with these alerts using Selenium WebDriver, which is a tool for testing websites. In this article, we will understand these features in more detail and will understand how we can automate various types of PopUps and Alerts in Selenium by covering the points in the following topics:
Why Handle Alerts?
What is Alert in Selenium?
Different types of Alerts/popups
How do you locate and interact with various Web alerts using WebDriver?
Why Handle Alerts?
Automated tests must be able to handle these alerts just like a human would. This means your Selenium WebDriver script needs to:
Detects the presence of an alert.
Read the message from the alert.
Accept or dismiss the alert.
Input text if it’s a prompt alert.
What is Alert in Selenium?
An Alert in Selenium is a small message box which appears on screen to give the user some information or notification. It notifies the user with some specific information or error, asks for permission to perform certain tasks and it also provides warning messages as well. Selenium provides an Alert interface to interact with these pop-ups.
JavaScript alerts are challenging to handle because they show up unexpectedly while we are testing a website. They can pop up at any time, interrupting your tests until you deal with them. Unlike other webpage elements, WebDriver cannot directly inspect or manipulate alerts, it requires specialized methods for interaction.
Application alerts shift your focus from the current browser window to a newly opened window and force the user to read the message displayed and act accordingly. Users will be blocked and will not be able to work further unless the alert message box gets handled.
What are the different types of Alerts/popups?
While automating any web application, Selenium WebDriver may encounter alerts that can either be application dependant or the Operating system dependant on which the user is working. Based on these categorizations, we can divide the alerts majorly into the following categories:
Windows/OS Alerts: Window-based alerts are system-generated alerts/popups. The developers invoke the operating system APIs to show these alerts/dialogue-boxes. Handling these alerts in Selenium is a little tricky and beyond the WebDriver's capabilities, as Selenium is an automation testing tool for web applications only, and we need third party utility to automate window based popups. A few of those utilities are AutoIT and Robot Class in Java.
Web/Javascript /Browser-based Alerts: Web/Browser based alerts are primarily called Javascript alerts and are those alerts that are browser dependant. These alerts are majorly called Popups.
In this blog, we will be focusing majorly on browser-based alerts, as they are more prevalent in this web era and are compatible with automation using Selenium WebDriver.
How do you locate and interact with various Web alerts using WebDriver?
When working with Selenium WebDriver, you can effectively locate and interact with JavaScript alerts using the provided methods. Let’s explore how to handle different types of alerts:
1.Simple Alert:
A simple alert displays a message and typically has an “OK” button.
To handle it, follow these steps:
Switch to the alert using driver.switchTo().alert().
Get the alert text using alert.getText().
Accept the alert by clicking the “OK” button with alert.accept().
The below code snippet shows how we can handle the mentioned alert using Selenium WebDriver:
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import io.github.bonigarcia.wdm.WebDriverManager;
public class SimpleAlertExample {
public static void main(String[] args) {
// Set up the WebDriver
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
//Navigate to the page with simple alert
driver.get("use your url link");
driver.findElement(By.xpath("Xpath of button")).click();
// Wait for the alert to be present
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.alertIsPresent());
//Switch to the alert
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
// Print the alert text
System.out.println("Alert message: " + alertText);
// Accept the alert
alert.accept();
// Close the browser
driver.quit();
}
}
Where,
The creation of the WebDriver instance happens, and the launch of the browser opens the website.
Reference variable is creates for Alert class which references to the alert by Alert alert = driver.switchTo().alert();.
To switch the control to the recently opened pop up window Driver.switchTo().alert(); is used
Alert is accepted using alert.accept(); method.
Finally, the driver closes the browser and ends the test session
2.Confirmation Alert:
A confirmation alert asks for user permission (usually with “OK” and “Cancel” buttons).
To handle it:
Switch to the alert using driver.switchTo().alert().
Accept (confirm) the alert with alert.accept().
Dismiss (cancel) the alert with alert.dismiss().
Here’s an example in Java using Selenium WebDriver:
public class ConfirmationAlertExample {
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.get("use your url link");
driver.findElement(By.xpath("Xpath of button")).click();
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
System.out.println("Alert message: " + alertText);
// Accept or dismiss the alert based on your requirement
// alert.accept(); // To accept
// alert.dismiss(); // To dismiss
driver.quit();
}
}
Here in this code first we are setting up the Chrome browser for automated testing using WebDriverManager, which automatically manages the setup of the ChromeDriver. It then opens a website that contains a button designed to trigger a confirmation alert when clicked. The script finds this button on the web page and clicks it, causing the confirmation alert to appear. Next, it waits until the alert is displayed using a WebDriverWait, which ensures that the code doesn't proceed until the alert is present. Once the alert is detected, the script switches the WebDriver's focus to the alert so it can interact with it. It retrieves the text from the alert and prints it to the console. Finally, the script decides how to handle the alert: it either accepts it by clicking the "OK" button or dismisses it by clicking the "Cancel" button. After dealing with the alert, the browser is closed, and the WebDriver session is ended. This process demonstrates how to automate the handling of a confirmation alert in a web browser using Selenium WebDriver with Java, making it easier to test web applications that use confirmation dialogs.
This script is useful for testing web applications that generate alerts and require user confirmation. It demonstrates how to interact with alerts and retrieve their messages using Selenium WebDriver. Remember to replace "use your url link" and "Xpath of button" with the actual URL and XPath of the element you want to interact with.
3.Prompt Alert: field along with the message.
A prompt alert asks for user input (usually with an input field).
To handle it:
Switch to the alert using driver.switchTo().alert().
Send text to the input field using alert.sendKeys("Your Text").
Accept or dismiss the alert as needed.
Here’s an example in Java using Selenium WebDriver:
public class PromptAlertExample {
public static void main(String[] args) throws InterruptedException {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.get("use your url link");
driver.findElement(By.xpath("Xpath of button")).click();
((JavascriptExecutor) driver).executeScript("arguments[0].click()", element);
Alert promptAlert = driver.switchTo().alert();
String alertText = promptAlert.getText();
promptAlert .sendKeys("User input"); // Enter your desired input
promptAlert .accept();
driver.quit();
}
}
Once the website launches, and we click the "prompt button", the prompt alert box opens.
To located the WebElement we have used javascript executor here ((JavascriptExecutor) driver).executeScript("arguments[0].click()", element);.This method executes JavaScript in the context of the currently selected frame or window.
It will read the text from the Alert box using String alertText = promptAlert.getText(); the value stores in the String format.
Alert.sendKeys is used to send user input text
Handling Unexpected Alerts
Unexpected alerts can disrupt your test flow. To handle them gracefully, you can use a try-catch block to catch UnhandledAlertException and decide on a course of action.
try {
// Your test steps here
} catch (UnhandledAlertException e) {
Alert alert = driver.switchTo().alert();
// Log the alert message or take a screenshot for debugging
alert.accept(); // or alert.dismiss();
}
Alert Presence in Different Browsers
Different browsers may handle alerts slightly differently. It’s important to test your alert handling code across all target browsers to ensure consistent behavior.
Debugging Alert Handling Issues
If your alert handling code isn’t working as expected, consider the following:
Ensure the XPath or selectors used to trigger the alert are correct.
Verify that the alert appears within the timeout period specified in WebDriverWait.
Check if there’s an iframe switch required before the alert appears.
Use debugging tools like breakpoints and logs to trace the execution flow.
Best Practices
Always validate the alert text to ensure your script is interacting with the correct alert.
Use try-catch blocks to handle scenarios where the alert does not appear as expected.
Clean up after handling the alert by switching the focus back to the main page or another frame if necessary.
Conclusion
Handling JavaScript alerts is a common requirement in web automation testing. By mastering the techniques discussed in this blog, you can ensure your Selenium WebDriver tests interact with alerts effectively. Remember to adapt these strategies to fit the specific needs of your application and keep your test scripts robust and reliable.
This extended content provides a more in-depth look at handling JavaScript alerts with Selenium WebDriver in Java, including best practices and troubleshooting tips. It’s designed to help you refine your automation scripts and overcome common challenges associated with alert handling. Keep exploring and enhancing your automation skills! Happy Testing!