ScreenshotNeo

BlogHow-to

How to Handle Alerts and Forms in Selenium with Java

Handle JavaScript alerts, prompts, confirmations, and HTML forms in Selenium with Java using explicit waits, runnable examples, and fixes for common failures.

By the ScreenshotNeo team4 October 202610 min read

Selenium handles browser-native JavaScript alerts, confirms, and prompts through its Alert interface. It handles ordinary HTML forms through located page elements such as inputs, buttons, and native selects. Use explicit waits for the state you need, then verify the result after an action.

This guide covers “JavaScript alerts, prompts and confirmations” and “Working with select list elements,” plus form entry, submission, synchronization, common failures, and a complete Java example. The same distinction matters when an in-page HTML modal looks like an alert: it is part of the document, so locate it as a page element.

1. Set up Selenium with Java

The examples use Selenium’s Java API. Add Selenium to your project using the dependency manager already used by your build. For Maven, add the Selenium Java dependency to pom.xml; use the version your project has selected. This example assumes a WebDriver instance named driver is already configured and the browser driver is available.

import java.time.Duration;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

Create an explicit wait around the driver:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

Ten seconds is an example, not a universal timeout. Choose a timeout that fits the application and test environment, and wait for the specific condition the next step requires.

2. Handle JavaScript alerts, prompts and confirmations

A JavaScript alert(), confirm(), or prompt() is a browser-native dialog, not a DOM element. Wait until the dialog exists, switch to it with driver.switchTo().alert() (or use the alert returned by the wait), read its text if useful, then accept or dismiss it.

Read and accept an alert

Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String message = alert.getText();
System.out.println(message);
alert.accept();

accept() activates the dialog’s affirmative action. For a simple alert, that closes it. For a confirmation dialog, it chooses OK.

Accept or cancel a confirmation

Alert confirmation = wait.until(ExpectedConditions.alertIsPresent());
String message = confirmation.getText();

if (shouldContinue) {
    confirmation.accept();
} else {
    confirmation.dismiss();
}

A confirmation dialog has accept and cancel behavior. Use dismiss() to exercise the cancel path. Assert the page outcome afterward; closing the dialog does not prove the application took the expected branch.

Enter text in a prompt

Alert prompt = wait.until(ExpectedConditions.alertIsPresent());
prompt.sendKeys("response text");
prompt.accept();

Prompts support response text. Ordinary alerts and confirms do not. To test a prompt’s cancel path, dismiss it without entering or submitting response text:

Alert prompt = wait.until(ExpectedConditions.alertIsPresent());
prompt.dismiss();

Native dialogs versus HTML modals

What you see How to interact
Browser-native JavaScript alert, confirm, or prompt Wait for alertIsPresent(); use Alert methods.
In-page modal built from HTML elements Locate its elements with By and interact with them as normal page elements.

An HTML modal may resemble a browser dialog visually, but it belongs to the document. Do not call switchTo().alert() for an ordinary page overlay.

3. Fill and submit a normal HTML form

Find form controls with stable locators, clear an editable field if it may already contain a value, type with sendKeys(), and click the actual submit button. Then wait for and inspect a known result.

WebElement email = wait.until(
    ExpectedConditions.visibilityOfElementLocated(By.name("email")));
email.clear();
email.sendKeys("reader@example.test");

WebElement submit = wait.until(ExpectedConditions.elementToBeClickable(
    By.cssSelector("form button[type='submit']")));
submit.click();

WebElement result = wait.until(
    ExpectedConditions.visibilityOfElementLocated(By.id("result")));
String confirmation = result.getText();
if (!confirmation.contains("received")) {
    throw new AssertionError("Unexpected form result: " + confirmation);
}

Replace the locators and expected message with those from the page under test. Selenium’s interaction guidance recommends clicking the applicable submit button in Selenium 4. A click does not itself guarantee that the next page state has loaded or that an asynchronous submission succeeded. Wait for the observable result you expect.

What the basic element operations do

Operation Use Watch for
sendKeys() Type into a keyboard-interactable control. The control must be present and interactable; clear existing text first when appropriate.
clear() Reset an editable field before entering a value. It is not a general way to reset every type of control.
click() Activate a button or other clickable control. Wait for clickability and then for the application’s resulting state.
submit() Legacy form submission operation on a form-associated element. Prefer clicking the actual submit button so the test follows the page’s real interaction path.

4. Work with select list elements

The Selenium Select helper is for a real HTML <select> containing <option> elements. Import org.openqa.selenium.support.ui.Select, locate the select, and choose by visible text or value.

WebElement countryElement = wait.until(
    ExpectedConditions.visibilityOfElementLocated(By.name("country")));
Select country = new Select(countryElement);
country.selectByVisibleText("Canada");

// Or select by the option's value attribute:
country.selectByValue("CA");

Choose one selection method that matches the markup and test intent. Other supported approaches include selectByIndex(int), deselectByVisibleText, deselectByValue, and deselectAll for multi-select controls. Check whether the control is multi-select before using deselection methods; they are not appropriate for a single-select list.

Since Selenium 4.5, a Select object cannot be created for a disabled <select>. Wait until the application enables it, or test that it remains disabled as appropriate.

Custom dropdowns are different

A dropdown made from div, li, buttons, or other ordinary elements is not a native select. Do not pass it to Select. Click the widget, locate its option elements, choose one, and wait for the selected state to appear.

WebElement dropdown = wait.until(ExpectedConditions.elementToBeClickable(
    By.cssSelector(".country-picker")));
dropdown.click();

WebElement option = wait.until(ExpectedConditions.elementToBeClickable(
    By.xpath("//li[normalize-space()='Canada']")));
option.click();

wait.until(ExpectedConditions.textToBePresentInElementLocated(
    By.cssSelector(".country-picker"), "Canada"));

Use locators that match the actual widget and its accessible structure. Some custom controls only render options after opening, so locate the option after the click.

5. Synchronize each interaction with the page

Use a condition-based explicit wait for the state the next action depends on: alert presence, element visibility, clickability, or the result after a submission. Selenium’s getting-started guidance notes that an implicit wait is rarely the best solution. Avoid mixing implicit and explicit waits because it can make wait timing harder to reason about.

  1. Wait for the control or dialog required by the next step.
  2. Perform one interaction.
  3. Wait for the resulting state, such as a confirmation message, selected value, or navigation target.
  4. Assert that the observable result matches the test expectation.

Choose conditions deliberately. Visibility is useful before reading text or typing; clickability is useful before clicking; alert presence is required before using Alert. If the page redraws after an action, locate the result again instead of keeping an old element reference.

6. Complete runnable example

This standalone example demonstrates a native JavaScript prompt, a native select, and a regular form submission. It uses a small data URL page so it does not depend on a third-party test site. Run it in a project with Selenium Java configured and a browser driver available to Selenium.

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

import org.openqa.selenium.Alert;
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.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

public class AlertsAndForms {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        try {
            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
            String html = """
                <!doctype html>
                <html><body>
                  <button id='ask' onclick=\"const answer = prompt('Your name?');\n                    document.getElementById('prompt-result').textContent = answer ?? 'cancelled';\">Ask</button>
                  <div id='prompt-result'></div>
                  <form onsubmit=\"event.preventDefault(); document.getElementById('result').textContent = 'Form received: ' + document.getElementById('email').value;\">
                    <input id='email' name='email'>
                    <select id='country' name='country'>
                      <option value='US'>United States</option>
                      <option value='CA'>Canada</option>
                    </select>
                    <button type='submit'>Send</button>
                  </form>
                  <div id='result'></div>
                </body></html>
                """;
            String dataUrl = "data:text/html;charset=utf-8," +
                URLEncoder.encode(html, StandardCharsets.UTF_8);
            driver.get(dataUrl);

            driver.findElement(By.id("ask")).click();
            Alert prompt = wait.until(ExpectedConditions.alertIsPresent());
            prompt.sendKeys("Avery");
            prompt.accept();
            WebElement promptResult = wait.until(
                ExpectedConditions.visibilityOfElementLocated(By.id("prompt-result")));
            if (!promptResult.getText().equals("Avery")) {
                throw new AssertionError("Prompt response was not applied");
            }

            WebElement email = wait.until(
                ExpectedConditions.visibilityOfElementLocated(By.name("email")));
            email.clear();
            email.sendKeys("reader@example.test");
            new Select(driver.findElement(By.id("country"))).selectByValue("CA");
            driver.findElement(By.cssSelector("button[type='submit']")).click();

            WebElement result = wait.until(
                ExpectedConditions.visibilityOfElementLocated(By.id("result")));
            if (!result.getText().contains("reader@example.test")) {
                throw new AssertionError("Form result did not contain the submitted email");
            }
        } finally {
            driver.quit();
        }
    }
}

The example’s page script prevents a network form submission and writes a result into the document, making the state easy to verify. For a real application, wait for its actual success message, updated record, URL, or other expected outcome.

7. Troubleshooting common failures

Symptom Likely cause Fix
NoAlertPresentException The code switches to an alert before it appears, or the page produced an HTML modal instead. Wait with alertIsPresent(). If it is an in-page modal, locate its DOM elements instead.
Prompt text is not entered The dialog is not a prompt, or the code did not target the current native dialog. Confirm the page opens a prompt and wait for alert presence before calling sendKeys().
UnexpectedTagNameException when creating Select The located element is not an HTML <select>, often because the UI is a custom dropdown. Inspect the markup. Use ordinary element clicks and waits for a custom widget.
Select construction fails on a disabled control The select is disabled; Selenium 4.5 and later reject creating a Select for it. Wait for it to become enabled, or verify disabled behavior without trying to select an option.
ElementNotInteractableException The element exists but is hidden, disabled, covered, or not yet ready. Wait for the relevant visible, enabled, or clickable state; verify the locator targets the user-facing control.
StaleElementReferenceException The page re-rendered and replaced the previously located element. Wait for the new state and locate the element again after the redraw.
Click returns but the test reads old content A click does not wait for an asynchronous response or final page state. Wait for a known result or navigation condition, then assert the result.
Form appears submitted but no success is verified The test treats the click as proof of application success. Assert a visible confirmation, changed page state, or other application-level outcome.
Waits take unexpectedly long or fail inconsistently Conditions do not match the next action, timeout assumptions are unsuitable, or implicit and explicit waits are mixed. Wait for the specific required condition and use a deliberate explicit timeout for the environment.

8. Performance, reliability, and cost

For reliable tests, prefer stable locators, explicit waits tied to observable conditions, and assertions on the result rather than fixed sleeps. Fixed delays waste time when a page is fast and may still be too short when it is slow. Re-find elements after a redraw. Keep test data controlled so validation errors and duplicate submissions do not obscure the interaction being tested.

This Selenium approach runs a browser and the test infrastructure around it, so execution time and compute cost depend on the browser, application, environment, and test volume. Reuse the browser session across related steps where the test design allows it, and close it in a finally block or equivalent cleanup to release resources. Native dialogs and forms themselves do not require a separate Selenium product fee; browser and infrastructure costs depend on where the suite runs.

9. Or skip the browser setup

If your task is to capture a page rather than test its interactive behavior, ScreenshotNeo is a website screenshot API and MCP server for developers. One GET request can return a PNG, JPEG, WebP, or PDF. See the ScreenshotNeo API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before the shot. Bot checks, blank pages, and failed loads are never billed. An MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 screenshots. [Get 1,000 screenshots a month free with no card]

10. FAQ

Can Selenium handle a browser alert without accepting it?

Yes. Read its text, then call dismiss() to take the cancel path for a confirm or prompt. A simple alert must be closed before normal page interaction can continue.

Can I use Select on a React or Vue dropdown?

Only if its rendered control is an actual HTML <select>. If it is built from ordinary elements, interact with those elements like other page controls.

Should I use a fixed sleep after submitting a form?

Usually not. Wait for the page condition that proves the expected outcome, such as a result message or destination URL.

No. Cookie consent banners are usually page elements, not native JavaScript dialogs. Locate and interact with them as DOM elements when the test requires it. For clean page captures, ScreenshotNeo removes supported consent banners before capture.

Sources