How to Handle Popups in Selenium?
1. Switch to the Alert
Use driver.switchTo().alert()
. This tells Selenium to focus on the alert instead of the main page.
2. Interact with the Alert
- Get the text: Use
alert.getText()
to read the message displayed in the alert. - Accept the alert: Use
alert.accept()
to click the “OK” button (or equivalent). - Dismiss the alert: Use
alert.dismiss()
to click the “Cancel” button (or equivalent). - Enter text (for prompts): Use
alert.sendKeys("text")
to input text in prompts before accepting or dismissing.
Example:
Java
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.Alert; import org.openqa.selenium.By; public class AlertHandlingDemo { public static void main(String[] args) { // Set the path to the ChromeDriver executable System.setProperty( "webdriver.chrome.driver" , "D:\\driver\\Feb\\chromedriver.exe" ); //path will be changes as per your chrome browser saved where // Initialize ChromeDriver WebDriver driver = new ChromeDriver(); // Navigate to the demoqa alerts page driver.get( "https://demoqa.com/alerts" ); // Click the button that triggers an alert driver.findElement(By.id( "alertButton" )).click(); // Switch to the alert Alert alert = driver.switchTo().alert(); // Get and print the alert text String alertText = alert.getText(); System.out.println( "Alert text: " + alertText); // Accept the alert after getting the alert text alert.accept(); // Close the browser driver.quit(); } } |
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.