Imagine that when filling an application, you accidentally missed certain information. Without an alert or pop-up window, how would you know this? This article provides into great depth on what a selenium alert is and how to deal with it. Let's take a look more closely at the following subjects to gain a practical understanding of handling alerts and popups in Selenium.
Introduction to Alerts in Selenium
In Selenium, an alert is a message or notice box that informs the user of particular information or requests authorization to continue a certain action. It can also be utilized as a warning.
There are three types of Alert in Selenium, described as follows:
- Simple Alert
This alert is used to notify a simple warning message with an ‘OK’ button as the image i attached below.
(Source:https://www.scientecheasy.com/)
- Prompt Alert
This alert will ask the user to input the required information to complete the task.
(Source:https://www.scientecheasy.com/)
- Confirmation Alert
This alert is basically used for the confirmation of some tasks.
(Source:https://www.scientecheasy.com/)
Methods to handle alerts in Selenium
- Void dismiss(): This method is used when the ‘Cancel’ button is clicked in the alert box.
driver.switchTo().alert().dismiss();
- Void accept(): This method is used to click on the ‘OK’ button of the alert.
driver.switchTo().alert().accept();
- String getText(): This method is used to capture the alert message.
driver.switchTo().alert().getText();
- Void sendKeys(String stringToSend): This method is used to send data to the alert box.
driver.switchTo().alert().sendKeys("Text");
The below code snippet demonstrates various ways of handling alerts using Selenium WebDriver in Java. To do the code explanation i used this Demo site
In the first method i have used switch.To method. In here i accept the alert message.
In the second method i create object from wait class and wait for the alert to appear and then accepts it.
In the third method using JavascriptExecutor override the "window.alert" function to suppress alerts by setting it to an empty function.
@Test
public void alert(){
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://testautomationpractice.blogspot.com/");
WebElement alertBtn = driver.findElement(By.xpath("//button[@id='alertBtn']"));
alertBtn.click();
//Using switchTo
Alert alert = driver.switchTo().alert();
alert.accept();
//Using Explicit wait
WebDriverWait mywait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert1 = mywait.until(ExpectedConditions.alertIsPresent());
alert1.accept();
//Using JavascriptExecutor
JavascriptExecutor js = (JavascriptExecutor) driver;
try{
js.executeScript("window.alert=function{};");
}catch(Exception e){
}
Top comments (0)