Selenium Alert Handling Exercises
JavaScript alerts are one of the most common Selenium interview topics — and a regular source of flaky tests when they appear late or unexpectedly. This practice set covers the three alert types, 10 hands-on exercises, the popups that aren't alerts, and model answers to the interview questions.
Practice Sites
- The Internet – JavaScript Alerts — simple, confirm and prompt alerts, with the result shown on the page for easy verification.
- DemoQA – Alerts — includes an alert that appears after 5 seconds.
- The Internet – Basic Auth — a browser authentication popup.
- DemoQA – Modal Dialogs — HTML modals, which are not alerts.
The Three Alert Types
| Type | Created by | Buttons | Selenium |
|---|---|---|---|
| Simple alert | alert("…") |
OK | accept() |
| Confirmation | confirm("…") |
OK / Cancel | accept() / dismiss() |
| Prompt | prompt("…") |
Text box + OK / Cancel | sendKeys(), then accept() / dismiss() |
All three are native browser dialogs. You can't inspect them or locate them with findElement().
Switch to them with:
driver.switchTo().alert();
Read the message with:
getText();
Solution Patterns
Simple Alert
Wait for the alert, read its text, and accept it.
WebDriverWait wait = new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
driver.findElement(
By.xpath("//button[text()='Click for JS Alert']")
).click();
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertEquals(
alert.getText(),
"I am a JS Alert"
);
alert.accept();
Assert.assertEquals(
driver.findElement(By.id("result")).getText(),
"You successfully clicked an alert"
);
Confirmation Alert
Dismiss the confirmation dialog.
driver.findElement(
By.xpath("//button[text()='Click for JS Confirm']")
).click();
wait.until(
ExpectedConditions.alertIsPresent()
).dismiss();
Assert.assertEquals(
driver.findElement(By.id("result")).getText(),
"You clicked: Cancel"
);
Prompt Alert
Enter text, accept the prompt, and verify the result.
driver.findElement(
By.xpath("//button[text()='Click for JS Prompt']")
).click();
Alert prompt = wait.until(
ExpectedConditions.alertIsPresent()
);
prompt.sendKeys("TestUser");
prompt.accept();
Assert.assertEquals(
driver.findElement(By.id("result")).getText(),
"You entered: TestUser"
);
These locators and messages match The Internet's alerts page.
Always wait with alertIsPresent() rather than switching immediately. This also handles delayed alerts.
A Reusable Alert Helper
public String acceptAlert(int seconds) {
Alert alert = new WebDriverWait(
driver,
Duration.ofSeconds(seconds)
).until(
ExpectedConditions.alertIsPresent()
);
String text = alert.getText();
alert.accept();
return text;
}
public boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
The helper returns the alert text so tests can assert against it.
Hands-On Exercises
- Simple alert: Trigger it, assert its text, accept it, and verify the page result.
- Confirm — accept: For example, confirm a delete and verify the record is gone.
- Confirm — dismiss: Cancel the action and verify nothing changed.
- Prompt — enter text: Type a value, accept, and verify it appears on the page.
- Prompt — dismiss: Type something, cancel, and verify nothing was submitted. The result shows
nullon The Internet. - Combined flow: Simple → accept; confirm → dismiss; prompt → type and accept; verify each result.
- NoAlertPresentException: Accept an alert, then call
switchTo().alert()again. Catch the exception, then rewrite the test usingisAlertPresent(). - Delayed alert: On DemoQA's 5-second alert, wait with
alertIsPresent()— noThread.sleep(). - Several alerts in a row: Accept the first, dismiss the second, and verify each outcome.
- Alert from an iframe: Switch into the frame, trigger the alert, handle it, then return with
switchTo().defaultContent(). The alert itself belongs to the browser, soswitchTo().alert()works the same way.
Popups That Aren't Alerts
| Popup | How to handle it |
|---|---|
| HTML / Bootstrap modal | It's part of the page. Locate it with findElement(), wait for visibility, and click its buttons. switchTo().alert() throws NoAlertPresentException. |
| New window or tab | Switch with window handles — see Windows & Tabs Practice. |
| Basic authentication popup | Put credentials in the URL (https://user:pass@host/path) or use Selenium 4's network authentication (BiDi/CDP). |
| Browser permission prompts | Disable or pre-grant them through browser options/preferences. |
| Native OS dialogs | Not reachable by WebDriver. Use sendKeys() on the file input for uploads or configure a download directory. |
Interview Questions — With Answers
1. Where do you handle alerts in your framework?
In a utility or BasePage method, such as acceptAlert(), that waits with alertIsPresent(), returns the text, and accepts or dismisses the alert. This prevents tests from repeating alert-handling code.
2. What's the difference between simple, confirmation and prompt alerts?
A simple alert has OK only. A confirmation alert has OK and Cancel. A prompt adds a text field along with OK and Cancel.
3. How do you handle an alert that appears after a delay?
Use an explicit wait:
wait.until(ExpectedConditions.alertIsPresent());
This waits until the alert is actually available.
4. What happens if an alert is left open when a test fails?
The next WebDriver command can throw UnhandledAlertException.
A good approach is to use a fresh browser per test with:
@AfterMethod(alwaysRun = true)
followed by:
quit();
You can also consider the unhandledPromptBehavior capability.
5. How do you avoid NoAlertPresentException?
Wait for the alert with alertIsPresent() instead of switching immediately. When an alert is optional, use a small isAlertPresent() helper.
6. How do you handle an unexpected alert?
Set the appropriate capability, for example:
options.setUnhandledPromptBehaviour(
UnexpectedAlertBehaviour.ACCEPT
);
You can also use DISMISS or the corresponding ..._AND_NOTIFY variants.
However, also investigate why the alert appears. An unexpected alert may indicate a real application problem.
7. How do you validate alert text before entering input?
Call getText() first and assert the expected message. Then use sendKeys() and accept().
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertEquals(
alert.getText(),
"Expected message"
);
alert.sendKeys("TestUser");
alert.accept();
8. Is an HTML modal an alert?
No. An HTML modal is a page element, so you locate and interact with it normally using WebDriver.
9. Do alerts cause problems in parallel runs?
Not if each thread has its own browser session, such as a ThreadLocal driver. An alert belongs to one browser session.
Problems can occur when multiple parallel tests share the same WebDriver instance.
10. Do alerts behave differently in Jenkins or headless mode?
JavaScript alerts work the same way in headless mode. CI failures usually come from timing, which makes waiting with alertIsPresent() especially important.
Scenario Questions to Practise
- Delete confirmation: Accept and verify the record is gone; dismiss and verify it still exists.
- Prompt username: Enter a name and verify it's shown; cancel and verify nothing changed.
- AJAX alert after 5 seconds: Wait for it without using
Thread.sleep(). - A random alert breaks tests: Handle it safely and report it if it shouldn't be there.
See how WebDriver commands such as switchTo() reach the browser in the Selenium WebDriver Visualizer.
For theory, see Alerts, Frames & Windows.
From Real Projects
In my automation roles I created, modified and enhanced Selenium WebDriver scripts in Java, organised with POM classes and a business library, and ran them with TestNG on Chrome and Firefox. Exercises like these build exactly the muscle memory you need when a real application — for me, Canolog's sales, inventory and service screens — throws a new kind of element at you. Switch back to the main content after handling an alert or frame, or the next step will fail.
Frequently Asked Questions
What are the Alert interface methods?
The main Alert interface methods are accept(), dismiss(), getText() and sendKeys().
How do you handle delayed alerts?
Wait with ExpectedConditions.alertIsPresent() before interacting with the alert.
How do you handle alerts inside an iframe?
Switch into the frame to trigger the alert, handle it with switchTo().alert(), then return to the main document with:
driver.switchTo().defaultContent();
Can Selenium handle authentication popups?
Not through the Alert interface. Use credentials in the URL or Selenium 4's network authentication capabilities.
Which site is best for alert practice?
The Internet's JavaScript Alerts page is useful because the result is displayed directly on the page. DemoQA's Alerts page is also useful, particularly for practising timed alerts.