Selenium · Browser automation foundations
How do you handle JavaScript alerts, confirms and prompts?
Short answer
Switch to the alert with driver.switchTo().alert(), then accept, dismiss, read getText or send keys for a prompt. Wait for the alert to be present and avoid trying to locate it with a normal element locator.
Native JavaScript dialogs are browser UI, not part of the DOM. WebDriver exposes them through the Alert interface. A normal findElement cannot see them, and if an alert is open it can block other commands.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String message = alert.getText();
alert.sendKeys("confirmed");
alert.accept();
wait.until(ExpectedConditions.not(ExpectedConditions.alertIsPresent()));- accept clicks OK and dismiss clicks Cancel or closes the dialog
- getText reads the message shown by the browser
- sendKeys writes into a prompt input; it throws on a plain alert
- alertIsPresent is the explicit wait to use before switching
- Unhandled alerts can cause later commands to fail with UnexpectedAlertPresentException
- Browser authentication dialogs and native file pickers are not JavaScript alerts
If the dialog only appears after an asynchronous action, wait for it rather than catching an exception. If it may or may not appear depending on state, treat both paths as explicit branches so the test still fails when the dialog is unexpectedly missing.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between accept and dismiss?
- 2How do you handle a prompt that needs text input?
- 3Why can an unhandled alert break later commands?
- 4Are browser authentication dialogs handled by the Alert API?
Say it in the interview
JavaScript dialogs are browser UI, so I switch to them through the Alert API instead of locating them as elements. I wait for alertIsPresent, read the text if needed, send keys only for prompts, then accept or dismiss. If an alert is left open, later commands can fail, so I wait for it to disappear as well. Basic auth and file pickers are different problems and need their own approach.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Selenium mock interview and get scored feedback on depth, clarity and confidence.