0
0
Selenium Javatesting~5 mins

Prompt alert text entry in Selenium Java

Choose your learning style9 modes available
Introduction

Prompt alerts ask the user to enter text. Testing this ensures your app handles user input correctly.

When a website asks for your name or email in a popup.
When confirming an action by typing a code in a prompt.
When testing form inputs that appear in alert popups.
When automating user input in popup dialogs during tests.
Syntax
Selenium Java
Alert alert = driver.switchTo().alert();
alert.sendKeys("your text here");
alert.accept();

Use switchTo().alert() to access the prompt alert.

sendKeys() inputs text into the prompt.

Examples
Enter "Hello" into the prompt and click OK.
Selenium Java
Alert alert = driver.switchTo().alert();
alert.sendKeys("Hello");
alert.accept();
Enter "12345" but then cancel the prompt.
Selenium Java
Alert alert = driver.switchTo().alert();
alert.sendKeys("12345");
alert.dismiss();
Sample Program

This test opens a page with a prompt alert, enters text, accepts it, and prints the result message.

Selenium Java
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class PromptAlertTest {
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://the-internet.herokuapp.com/javascript_alerts");
            driver.findElement(By.xpath("//button[text()='Click for JS Prompt']")).click();

            Alert alert = driver.switchTo().alert();
            alert.sendKeys("Selenium Test");
            alert.accept();

            String resultText = driver.findElement(By.id("result")).getText();
            System.out.println(resultText);
        } finally {
            driver.quit();
        }
    }
}
OutputSuccess
Important Notes

Always switch to the alert before interacting with it.

Use accept() to click OK and dismiss() to click Cancel.

Make sure the alert is present before switching to avoid errors.

Summary

Prompt alerts let users enter text in popups.

Use sendKeys() to input text in Selenium.

Always accept or dismiss the alert to continue the test.