SELENIUM : How do you handle alerts using Selenium WebDriver in Java?
SDET Automation Testing Interview Questions & Answers
We will be covering a wide range of topics including QA manual testing, automation testing, Selenium, Java, Jenkins, Cucumber, Maven, and various testing frameworks.
SELENIUM : How do you handle alerts using Selenium WebDriver in Java?
To handle alerts using Selenium WebDriver in Java, you can use the switchTo().alert() method to switch the driver's focus to the alert box. Once the focus is on the alert box, you can use the accept() or dismiss() method to either accept or dismiss the alert.
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class AlertHandling {
public static void main(String[] args) {
// Create a new instance of the ChromeDriver
WebDriver driver = new ChromeDriver();
// Navigate to the page with the alert
driver.get("https://www.example.com/page");
// Locate the element that triggers the alert by ID and click it
driver.findElement(By.id("trigger-alert")).click();
// Switch the driver's focus to the alert box
Alert alert = driver.switchTo().alert();
// Get the text of the alert and print it
String alertText = alert.getText();
System.out.println("Alert text: " + alertText);
// Accept the alert
alert.accept();
}
}
This code navigates to a page, clicks an element that triggers an alert, switches the driver's focus to the alert box using the switchTo().alert() method, gets the text of the alert using the getText() method, prints it to the console, and accepts the alert using the accept() method.