Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk5 min

How to Handle Alerts and Forms in Selenium with Java

Use Selenium’s Alert API for native JavaScript dialogs, WebElement actions for forms, and Select only for real HTML select controls. Learn the Java patterns and synchronization practices that make each interaction reliable.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Selenium’s Alert interface for browser-native JavaScript alerts, confirmations, and prompts; use ordinary WebElement operations for HTML forms. For a native HTML dropdown, use Selenium’s Select helper. For custom dropdowns and in-page modals, interact with their document elements instead. In each case, wait for the required state and verify the result rather than assuming that a click succeeded.

Handle JavaScript alerts, prompts and confirmations

A JavaScript alert, confirm, or prompt is a browser-native dialog, not an element in the page’s HTML. Switch to it through WebDriver’s alert interface. If it appears asynchronously, wait until it is present before reading or acting on it. Selenium’s official JavaScript alerts, prompts and confirmations documentation describes these dialog types and their supported actions.

Read and accept an alert or confirmation

import java.time.Duration;

import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(ExpectedConditions.alertIsPresent());

String message = alert.getText();
alert.accept();

accept() confirms the dialog. For a confirmation box, use dismiss() to choose its cancel path instead. The timeout in this example is illustrative: choose a wait duration appropriate to the application and test environment.

Enter text in a prompt

Only a prompt accepts response text. Set it before accepting; to cancel the prompt, dismiss it without entering a response.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Alert prompt = wait.until(ExpectedConditions.alertIsPresent());
prompt.sendKeys("response text");
prompt.accept();

Ordinary alerts and confirmations do not accept prompt text. If the expected native dialog never appears, do not try to locate it as a page element: first establish whether the application triggered it, then wait for the dialog before interacting.

Distinguish a browser dialog from an HTML modal

A browser-native JavaScript dialog is handled with WebDriver’s alert interface. An HTML modal is part of the document, so locate its markup and use normal element interactions. The two may look similar on screen, but they are different browser contexts and require different Selenium operations.

Fill and submit a normal HTML form

Find controls with locators that match the page under test. Use clear() before sendKeys() when the test needs to replace existing editable text. Selenium’s element interaction guidance covers these operations and recommends clicking the applicable submit button in Selenium 4.

import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

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

WebElement email = wait.until(
    ExpectedConditions.visibilityOfElementLocated(By.name("email")));
email.clear();
email.sendKeys("[email protected]");

driver.findElement(By.cssSelector("form button[type='submit']")).click();

WebElement result = wait.until(
    ExpectedConditions.visibilityOfElementLocated(By.id("result")));
String confirmation = result.getText();

This assumes the page has an editable control named email, a matching submit button, and a result element with ID result. Replace those locators with ones from the page being tested. Assert that confirmation contains the expected outcome; the click itself is not evidence that the form was accepted.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Wait for the state needed by the next action

Choose a wait condition for the operation about to happen: visibility before reading or typing, clickability before clicking, an alert before switching to a native dialog, or a known result after submission. Selenium notes that a click does not itself wait for a subsequent page load, and an application may continue processing after navigation. Find elements again after a redraw instead of relying on an old reference that may have become stale. See the Java API’s WebElement reference and Selenium’s first-script guidance.

A single implicit-wait setting is not a universal synchronization strategy. Selenium’s introductory guidance says implicit waits are rarely the best solution; condition-based waits make the test’s expected state explicit.

Choose a native select or interact with a custom dropdown

Use Select for an actual HTML <select>

Wrap the native select element in Selenium’s Select helper, then choose by visible text or value. The helper is intended for HTML <select> and <option> elements, not every control that looks like a dropdown.

import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.Select;

Select country = new Select(driver.findElement(By.name("country")));
country.selectByVisibleText("Canada");
// Alternatively: country.selectByValue("CA");

Confirm that the locator identifies a real select element and that the option’s text or value matches the page. Selenium’s Working with select list elements documentation notes that since Selenium 4.5, a Select object cannot be created for a disabled select.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use ordinary element actions for a custom dropdown

A JavaScript widget built from elements such as div or li is not a native select. Locate and click the widget, locate the desired option, click it, and wait for a selected-state indicator or other expected page change. Passing such a widget to Select is the wrong interaction model.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot common failures

  • No alert is present: the dialog may not have been triggered yet, or the application may show an HTML modal instead. Wait for the native alert only when that is the expected browser state; otherwise locate the modal in the document.
  • Element cannot be interacted with: it may not yet be visible or enabled, or the locator may match the wrong control. Wait for the condition required by the next action and check the locator against the live page structure.
  • Click appears to do nothing: a click does not prove submission or wait for all application work to finish. Wait for a known confirmation, URL change, or other application-specific outcome and assert it.
  • Stale element reference after submission: a redraw can replace the element. Locate the result or control again after the state change instead of reusing the old reference.
  • Select rejects the target: verify the element is a native <select>, not a custom widget. Also check whether the select is disabled; Selenium 4.5 and later do not allow constructing a Select for one.
  • Typed text is appended unexpectedly: clear an editable field before sending replacement text. A control that is not editable cannot be reset this way.

Or skip the browser setup

If your task is to capture a page image or PDF rather than test Selenium interactions, ScreenshotNeo offers a one-request screenshot API. For example, this cURL request saves a screenshot as WebP:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo documentation for request options. ScreenshotNeo accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; those cleanup steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Every feature is available on every plan. Sign up for free ScreenshotNeo access.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.