click one below link to download video: https://dkw8gemxc9npb.cloudfront.net/...
The Alert class in Selenium is used to handle alerts, confirmation dialogs, and prompts that appear on the webpage. An alert is a small dialog box that pops up on the screen to inform the user about a specific action that needs to be taken.
To use the Alert class, you need to first switch to the alert using the driver.switchTo().alert() method.
Once you have switched to the alert, you can perform various actions such as accepting or dismissing the alert, getting the text displayed on the alert, and sending input to the prompt dialog.
you can see the sample Alert on screen
This alert is used to notify a simple warning message with an ‘OK’ button, as shown in the below snapshot.
Here is an example on screen to handle an alert using Java code in Selenium:
import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Alert Example {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");
driver.findElement(By.xpath("//button[contains(text(), 'Click Me')]")).click();
Alert alert = driver.switchTo().alert(); // switch to alert
String alertText = alert.getText(); //This method is used to capture the alert message.
System.out.println("Alert text: " + alertText);
alert.accept(); //This method is used to click on the ‘OK’ button of the alert.
(or)
alert().dismiss(); //This method is used when the ‘Cancel’ button is clicked in the alert box.
(or)
alert().sendKeys("Text"); //This method is used to send data to the alert box.
driver.quit();
}
}
In this example, we first set the path to the Chrome driver executable and create a new ChromeDriver object. We then navigate to the example.com webpage and click a button that triggers an alert. We then switch to the alert using the driver.switchTo().alert() method and get the text displayed on the alert using the alert.getText() method. We can then accept the alert using the alert.accept() method or cancel the alert using the alert().dismiss() method or send data to the alert box using the alert().sendKeys("Text") method and quit the driver.