Handling Web Dialog Box/Popup Window using Selenium
1. Navigate to the webpage “https://demoqa.com/alerts“.
2. Locate and click the button that triggers the alert dialog.
3. Wait for the alert to be present using WebDriverWait.
4. Switch to the alert and print its text.
5. Accept the alert (click OK).
6. Close the browser.
Java
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class HandleWebDialogBox { public static void main(String[] args) { // Set the path to the ChromeDriver executable. System.setProperty( "webdriver.chrome.driver" , "D:\\driver\\Feb\\chromedriver.exe" ); // Initialize ChromeDriver. WebDriver driver = new ChromeDriver(); // Navigate to the website. driver.get( "https://demoqa.com/alerts" ); // Find and click the "Click me" button to trigger the dialog box. WebElement clickMeButton = driver.findElement(By.id( "alertButton" )); clickMeButton.click(); // Explicitly wait for the alert to be present. WebDriverWait wait = new WebDriverWait(driver, 10 ); wait.until(ExpectedConditions.alertIsPresent()); // Switch to the alert. org.openqa.selenium.Alert alert = driver.switchTo().alert(); // Get the text from the alert and print it. System.out.println( "Alert Text: " + alert.getText()); // Accept the alert (clicking OK). 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.