Example of Alert Handling Using Selenium
- Launch the web browser and open the webpage “https://demoqa.com/alerts“
- Click on the confirmation alert button
- Accept the alert
- Click on the confirmation alert button again
- Reject the alert
Selenium test Script to Handle Alerts:
Java
package GFG_Maven.GFG_MAven; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.chrome.ChromeDriver; public class Geeks { public static void main(String args[]) throws InterruptedException { System.setProperty( "webdriver.chrome.driver" , "C:\\Users\\ADMIN\\Documents\\chromedriver.exe" ); ChromeDriver driver = new ChromeDriver(); // Maximize the browser driver.manage().window().maximize(); // Launch Website driver.get( "https://demoqa.com/alerts" ); // clicking on prompt button driver.findElement(By.xpath( "//*[@id=\"confirmButton\"]" )).click(); Thread.sleep( 3000 ); // accepting javascript alert Alert alert = driver.switchTo().alert(); alert.accept(); // clicking on prompt button driver.findElement(By.xpath( "//*[@id=\"confirmButton\"]" )).click(); Thread.sleep( 3000 ); // Rejecting javascript alert Alert alert1 = driver.switchTo().alert(); alert1.dismiss(); } } |
Output:
The program will open the website and click on the confirmation alert button and accept the alert and again it click the alert button and decline the alert.
How to Handle Alert in Selenium using Java?
Imagine filling out a form online and accidentally missing some information. You only know if you made a mistake if the website tells you somehow, like with a pop-up message. This article explains what those pop-up messages are called in Selenium (alerts) and how to deal with them in your automated tests.