Junior QASeleniumFree question
How do you handle alerts, popups and frames in Selenium?
60-second answer
For JavaScript alerts, confirms and prompts, I switch to the alert with driver.switchTo().alert(), then use accept, dismiss, getText or sendKeys, ideally after an explicit wait for alertIsPresent. For iframes, I must switch into the frame before interacting with its elements, using switchTo().frame by index, name or id, or WebElement, and then switch back with defaultContent or parentFrame. HTML modal popups aren't alerts; they're normal page elements, so I just locate and click them.
Explanation
- Alert methods:
accept(),dismiss(),getText(),sendKeys()(prompt only). NoAlertPresentExceptionif no alert;UnhandledAlertExceptionif an alert blocks other actions.- Frames:
frame(int),frame(String nameOrId),frame(WebElement);parentFrame()goes up one level;defaultContent()goes to the top. - Use
ExpectedConditions.frameToBeAvailableAndSwitchToIt(...). - Browser permission popups (location, notifications) are handled with browser options, not Selenium alerts.
Example
A payment form is inside an iframe from the payment gateway. Switch into it, type the card number, switch back to click "Place order".
Sample code
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// JS confirm
driver.findElement(By.id("delete")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
Assert.assertEquals(alert.getText(), "Are you sure?");
alert.accept();
// iframe
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe#card")));
driver.findElement(By.name("cardnumber")).sendKeys("4111111111111111");
driver.switchTo().defaultContent();
driver.findElement(By.id("place-order")).click();