About this lesson
Handle a prompt alert in Selenium Java: type into the dialog with sendKeys()
Learn Selenium JavaIntermediateAlerts & Popups
How it works
A prompt dialog, from JavaScript's prompt(), has a text box. Alert.sendKeys() types into it, and accept() sends the text back to the page. dismiss() cancels, and the page receives no text at all.
The prompt on the Alerts page opens with default text already in the box. In Chrome, sendKeys() replaces that text rather than adding to it, and a second sendKeys() replaces it again, so there is no separate clear step. Accepting without typing sends the default.
Only prompts accept typing. sendKeys() on a simple alert or a confirm throws ElementNotInteractableException.
About the assignment
The prompt asks for a name and writes what it receives into promptResult. You type the word from the task into the dialog, accept it, and print what the page recorded.
What you will do
- Click the prompt button, located by its label.
- Switch to the alert and send the word from the task with
sendKeys(). - Accept the prompt.
- Read
promptResultand print its text after the labelResult:.
Common mistakes
Accepting before typing
The page receives the default text, so the result shows the wrong word.
Dismissing instead of accepting
Cancel throws the typed text away and the page reports that the prompt was cancelled.
Expecting getText() to show the typed text
getText()on the alert returns only the question, never what you typed, so check the result inpromptResulton the page.
In a real test suite
Prompts are rare in production apps but common in legacy admin tools and training sites. The same Alert API covers them, and the habit of checking the page's reaction after the dialog carries over to every kind of popup.
Lesson 41 answered a confirm. Lesson 43 handles two alerts that open one after the other.
Related lessons
- Handle Confirm AlertConfirm dialogs, which have OK and Cancel but no text box.
- Type Text with sendKeys()
sendKeys()on page inputs, where typing appends instead. - Handle Sequential AlertsHandle dialogs that arrive one after another.
To try one of these calls on any page without a task, open the Online Selenium Java Compiler.
Starter code
The editor above opens with this code. Fill in the TODO lines, then run and submit it.
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class Main {
public static void main(String[] args) throws Exception {
WebDriver driver = new ChromeDriver();
driver.get("https://testkru.com/Interactions/Alerts");
// TODO: Click "Show Prompt"
// TODO: Clear default text and type "Selenium" in the prompt
// TODO: Accept the prompt
// TODO: Print the result from promptResult element
driver.quit();
}
}