This guide shows you how to automate browser alerts and web forms using Selenium WebDriver with Java. You’ll learn to accept, dismiss, and read alert text, plus how to fill inputs, select dropdowns, and submit forms reliably. By the end, you’ll have reusable code patterns for common UI interactions.
What You’ll Need
- Java Development Kit (JDK) 8 or later
- Maven or Gradle for dependency management (or manually add Selenium jars)
- Selenium Java client library (version 4.x recommended)
- A WebDriver binary (e.g., ChromeDriver, GeckoDriver) matching your browser
- An IDE like IntelliJ IDEA or Eclipse
- Basic knowledge of Java and HTML selectors
Step-by-Step
- Set up your project – Create a Maven project and add the Selenium dependency to your
pom.xml:<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.21.0</version> </dependency>
For Gradle, add
implementation 'org.seleniumhq.selenium:selenium-java:4.21.0'tobuild.gradle. - Initialize the WebDriver – Set the system property for your driver and instantiate it:
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver();For Firefox, use
webdriver.gecko.driverandnew FirefoxDriver(). - Navigate to the page containing the alert or form – Use
driver.get("https://example.com"). - Handling JavaScript alerts – When an alert pops up, switch to it using
Alert alert = driver.switchTo().alert();. Then you can:- Get its text:
String text = alert.getText(); - Accept it:
alert.accept(); - Dismiss it:
alert.dismiss(); - Send keys (for prompt alerts):
alert.sendKeys("input text");
Always call
accept()ordismiss()to close the alert; otherwise subsequent commands will hang. - Get its text:
- Handling confirmation and prompt dialogs – The same
Alertinterface works for confirm and prompt dialogs. For a confirm, useaccept()for OK ordismiss()for Cancel. For a prompt, callsendKeys()before accepting. - Locating form elements – Use
driver.findElement(By.id("username")),By.name("email"),By.cssSelector("input[type='password']"), orBy.xpath("//form[@id='login']//input[1]"). Prefer IDs and names as they are stable. - Clearing and filling text fields – Before typing, clear any existing value:
WebElement input = driver.findElement(By.id("username")); input.clear(); input.sendKeys("testuser");Use
sendKeys()to simulate typing. For large text areas, the same method works. - Selecting checkboxes and radio buttons – Check if it’s already selected, then click if needed:
WebElement checkbox = driver.findElement(By.id("subscribe")); if (!checkbox.isSelected()) { checkbox.click(); }Radio buttons work the same way; click the one you want.
- Handling dropdowns (select elements) – Use the
Selectclass for native<select>elements:Select dropdown = new Select(driver.findElement(By.id("country"))); dropdown.selectByVisibleText("United States"); // or dropdown.selectByValue("us"); // or dropdown.selectByIndex(3);For custom dropdowns (non-
<select>), click the element to open it, then click the option by text or value. - Submitting the form – You can either click the submit button or call
submit()on any element inside the form:driver.findElement(By.id("submit")).click(); // or driver.findElement(By.id("username")).submit();Using
submit()triggers the form’s default submission behavior, which is often more reliable than clicking a button that might have custom JavaScript. - Waiting for elements – Use explicit waits to avoid race conditions:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement submitBtn = wait.until(ExpectedConditions.elementToBeClickable(By.id("submit"))); submitBtn.click();This is especially important after submitting, as the page may reload or show a success message.
- Handling alerts that appear after form submission – After clicking submit, an alert may appear. Wait for it with
wait.until(ExpectedConditions.alertIsPresent()), then switch and handle it.
Common Mistakes
- Forgetting to switch to the alert before interacting with it – you must call
driver.switchTo().alert(). - Not clearing text fields before sending keys, causing text to append instead of replace.
- Using
Thread.sleep()instead of explicit waits, leading to flaky tests. - Assuming a dropdown is a native
<select>when it’s a custom widget – theSelectclass will throw an exception. - Clicking a button that is disabled or not yet visible – always wait for clickability.
- Not handling the alert at all, causing the WebDriver to hang on the next command.
Tips
- Use
By.id()orBy.name()whenever possible; they are most stable. - For file uploads, use
sendKeys("path/to/file")on the input element of type file – do not click it. - If a form has multiple submit buttons, use
submit()on a field to trigger the default action. - Always close the driver in a
finallyblock or use try-with-resources to avoid leaking browser processes. - For alerts, wrap the handling in a try-catch to gracefully handle cases where no alert appears.
- Use page object model (POM) to keep locators and actions organized.
Troubleshooting
- Alert not found – The alert may appear after a delay. Use
WebDriverWaitwithExpectedConditions.alertIsPresent()before switching. - NoSuchElementException – The element is not in the DOM. Check your locator, wait for visibility, or ensure you’re on the correct page/frame.
- Element not clickable – The element is covered by another element or off-screen. Scroll into view using
JavascriptExecutoror wait for it to be clickable. - StaleElementReferenceException – The page has changed after you located the element. Re-find the element after any navigation or DOM change.
- Alert not dismissed – If you call
accept()but the alert still appears, you might be handling a different alert (e.g., a second one). Check for multiple alerts in sequence. - Select class not working – The element may not be a native
<select>. Inspect the HTML; if it’s a div-based dropdown, you need to click and then select an option by text.
Frequently Asked Questions
How do I handle an alert that appears after a delay?
Use an explicit wait: new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.alertIsPresent()) before calling switchTo().alert().
What is the difference between accept() and dismiss()?
accept() clicks the OK/Yes button, while dismiss() clicks Cancel/No. For prompt dialogs, you must send keys before accepting.
Can I handle multiple alerts in a row?
Yes, but you must handle them sequentially. After accepting the first, check for the next with a wait, then switch and handle it.
How do I select an option from a custom dropdown?
Click the dropdown to open it, then find the option element (often a <li>) and click it. Use text or value to locate it.
Why is my form submission not working?
Check if the button is disabled, if there are validation errors, or if the form uses AJAX. Wait for the button to be clickable, and consider using submit() on a field instead of clicking the button.
How do I handle file uploads?
Locate the <input type="file"> element and use sendKeys("absolute/path/to/file"). Do not click the element; it will open a native dialog that Selenium cannot control.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Campus Tech Innovation Hubs: What They Are
- Poco C51 Airtel Prepaid Locked Variant India?
- Jenkins vs GitHub Actions: Which CI/CD Fits Your Team?
- Turn Off Backup Encryption in iTunes?
- Shared VPS Hosting: Is It Better?
- Disk Defrag Pro: What It Does and Whether You Need It