Prompt Alerts in Selenium WebDriver
A Prompt Alert is a native JavaScript dialog that allows a web application to display a message and request text input from the user. Unlike a simple JavaScript alert, a prompt contains a text input field along with OK and Cancel buttons. Selenium WebDriver provides the Alert interface to interact with prompt dialogs, including reading their text, entering a value, accepting the prompt, and dismissing it.
Prompt dialogs are commonly used when an application needs a small piece of information from the user, such as a name, username, confirmation code, search value, employee ID, or other text input. In Selenium, prompt dialogs are handled through the Alert interface.
For complete Selenium WebDriver training and practical automation learning, visit Selenium Training and Register for Course Demo.
1. What is a Prompt Alert?
A Prompt Alert is a JavaScript-based browser dialog that asks the user to enter some text. It is generally created using JavaScript's prompt() function.
prompt("What is your name?");
The browser displays a dialog containing a message, a text input area, an OK button, and a Cancel button.
Prompt Alert
|
"What is your name?"
|
+-------------------+
| Enter your name |
| |
| OK Cancel |
+-------------------+
/ \
OK Cancel
| |
Submit Input Cancel
Operation Operation
2. Why are Prompt Alerts Used?
Prompt alerts are used when an application needs a small amount of user input before continuing an operation.
Common examples include:
- Entering a user's name.
- Entering an employee ID.
- Entering a product quantity.
- Entering a search keyword.
- Entering a confirmation value.
- Entering a temporary code.
- Entering a username.
- Providing information before an operation continues.
3. JavaScript prompt() Function
The JavaScript prompt() function can be used to display a prompt dialog.
let name = prompt("What is your name?");
The value entered by the user is returned by the prompt when the user selects OK. If the user selects Cancel, the application receives the cancellation result rather than submitted prompt text.
4. Prompt Alert Example
<button onclick="getName()">Enter Name</button>
<script>
function getName() {
let name = prompt("What is your name?");
if (name !== null) {
alert("Hello " + name);
}
}
</script>
When the button is clicked, the browser displays a prompt asking the user to enter a name.
5. Prompt Alert Structure
Button Click
↓
JavaScript prompt()
↓
Prompt Alert Appears
↓
User Enters Text
↓
┌─────────────┐
↓ ↓
OK Cancel
↓ ↓
Submit Text Cancel Input
↓ ↓
Application Application
Continues Continues
6. Types of JavaScript Dialogs
| Dialog | JavaScript Function | Input Field | OK | Cancel |
| Alert | alert() | No | Yes | No separate Cancel option |
| Confirmation | confirm() | No | Yes | Yes |
| Prompt | prompt() | Yes | Yes | Yes |
Selenium provides a WebDriver API for working with native JavaScript popup types.
7. Prompt Alert vs Confirmation Alert
| Feature | Confirmation Alert | Prompt Alert |
| JavaScript Function | confirm() | prompt() |
| Message | Yes | Yes |
| Text Input | No | Yes |
| OK | Yes | Yes |
| Cancel | Yes | Yes |
| Selenium API | Alert | Alert |
| Input Method | Not normally required | sendKeys() |
8. Selenium Alert Interface
Selenium uses the Alert interface to interact with native browser dialogs. The interface provides methods for retrieving the dialog message, accepting the dialog, dismissing it, and entering response text when the dialog supports input.
| Method | Purpose |
getText() | Gets the text displayed by the alert. |
accept() | Accepts the prompt, normally selecting OK. |
dismiss() | Dismisses the prompt, normally selecting Cancel. |
sendKeys() | Enters text into a prompt dialog. |
9. Switching to a Prompt Alert
Before interacting with a prompt alert, Selenium needs to switch the WebDriver's context to the active alert.
Alert alert = driver.switchTo().alert();
After obtaining the Alert object, the test can read its message, enter text, accept it, or dismiss it.
10. Basic Prompt Alert Workflow
Click Button
↓
prompt() Executes
↓
Prompt Alert Appears
↓
Wait for Alert
↓
switchTo().alert()
↓
Read Prompt Text
↓
sendKeys()
↓
accept() / dismiss()
↓
Verify Application Result
11. Getting Prompt Alert Text
The prompt message can be retrieved using getText().
Alert alert = driver.switchTo().alert();
String message = alert.getText();
System.out.println("Prompt Message: " + message);
Reading the prompt text is useful for validating that the correct dialog has appeared before entering any information.
12. Entering Text into a Prompt Alert
For a prompt dialog, Selenium provides sendKeys() through the Alert API.
Alert alert = driver.switchTo().alert();
alert.sendKeys("Selenium");
The sendKeys() method is specifically useful when the active dialog is a prompt that accepts text input.
13. Accepting a Prompt Alert
After entering the required text, use accept() to select the OK option.
Alert alert = driver.switchTo().alert();
alert.sendKeys("Manish");
alert.accept();
The entered value is then submitted to the web application according to the application's JavaScript logic.
14. Dismissing a Prompt Alert
The dismiss() method selects the Cancel option of the prompt.
Alert alert = driver.switchTo().alert();
alert.dismiss();
When the prompt is dismissed, the entered text is not submitted through the prompt.
15. Complete Prompt Alert Example
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) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
driver.findElement(
By.id("promptButton")
).click();
Alert alert = driver.switchTo().alert();
System.out.println(
"Prompt: " + alert.getText()
);
alert.sendKeys("Selenium");
alert.accept();
driver.quit();
}
}
16. Prompt Alert with Explicit Wait
A prompt may not appear immediately after clicking a button. For dynamic applications, an explicit wait can be used with ExpectedConditions.alertIsPresent().
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
alert.sendKeys("Selenium");
alert.accept();
17. Complete Prompt Test with Explicit Wait
import java.time.Duration;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class PromptAlertWaitTest {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
driver.get("https://example.com");
driver.findElement(
By.id("promptButton")
).click();
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
String message = alert.getText();
System.out.println(
"Prompt Message: " + message
);
alert.sendKeys("Selenium");
alert.accept();
driver.quit();
}
}
18. Why Use Explicit Wait for Prompt Alerts?
The prompt may be displayed after JavaScript processing or another application action. If Selenium tries to switch to the alert before it exists, the test can fail.
Click Button
↓
JavaScript Processing
↓
Prompt Appears
↓
Selenium Detects Prompt
↓
Interact with Prompt
An explicit wait synchronizes the test with the condition that the alert is actually present.
19. Thread.sleep() vs WebDriverWait
A fixed delay can be used in a basic demonstration, but it is generally less precise than waiting for the specific alert condition.
driver.findElement(
By.id("promptButton")
).click();
Thread.sleep(3000);
Alert alert = driver.switchTo().alert();
alert.sendKeys("Selenium");
alert.accept();
Recommended approach:
driver.findElement(
By.id("promptButton")
).click();
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
alert.sendKeys("Selenium");
alert.accept();
20. Validating Prompt Text
Before entering the value, the test can validate the prompt message.
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
String actualText = alert.getText();
String expectedText =
"Enter your name";
Assert.assertEquals(
actualText,
expectedText
);
alert.sendKeys("Manish");
alert.accept();
21. Prompt Alert with TestNG
import java.time.Duration;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.Test;
public class PromptAlertTest {
@Test
public void verifyPromptAlert() {
WebDriver driver = new ChromeDriver();
try {
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
driver.get(
"https://example.com"
);
driver.findElement(
By.id("promptButton")
).click();
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertEquals(
alert.getText(),
"Enter your name"
);
alert.sendKeys("Manish");
alert.accept();
} finally {
driver.quit();
}
}
}
22. Verifying Entered Prompt Value
A strong test should verify not only that text was entered into the prompt, but also that the application received and processed the expected value.
String name = "Manish";
driver.findElement(
By.id("promptButton")
).click();
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
alert.sendKeys(name);
alert.accept();
String displayedName =
driver.findElement(
By.id("result")
).getText();
Assert.assertEquals(
displayedName,
name
);
23. Prompt Alert with Default Text
A prompt may contain default or initial text depending on how the JavaScript prompt is created. Selenium can enter a new value through sendKeys().
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
alert.sendKeys("New Value");
alert.accept();
24. JavaScript Prompt with Default Value
let name = prompt(
"Enter your name",
"Guest"
);
The second argument provides an initial value for the prompt.
Selenium can replace the existing prompt response using:
Alert alert = driver.switchTo().alert();
alert.sendKeys("Manish");
alert.accept();
25. Prompt Alert Cancel Scenario
The Cancel path should also be automated because a real user may choose not to provide the requested value.
driver.findElement(
By.id("promptButton")
).click();
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertEquals(
alert.getText(),
"Enter your name"
);
alert.dismiss();
26. Prompt Alert Accept vs Dismiss
| Method | User Action | Prompt Result |
accept() | OK | Prompt response is submitted. |
dismiss() | Cancel | Prompt is cancelled and the response is not submitted. |
27. Prompt Alert Flow with Accept
Prompt Appears
↓
Read Message
↓
Enter Text
↓
sendKeys("Selenium")
↓
accept()
↓
Application Receives Value
↓
Verify Result
28. Prompt Alert Flow with Cancel
Prompt Appears
↓
Read Message
↓
dismiss()
↓
Input Not Submitted
↓
Verify Cancel Behavior
29. Prompt Alert and NoAlertPresentException
If Selenium tries to interact with a prompt when no alert is displayed, an alert-related exception can occur.
Alert alert =
driver.switchTo().alert();
If the prompt is not present, Selenium can report a no-alert condition.
try {
Alert alert =
driver.switchTo().alert();
alert.sendKeys("Selenium");
alert.accept();
} catch (NoAlertPresentException e) {
System.out.println(
"Prompt alert was not present."
);
}
30. Handling Optional Prompt Alerts
If a prompt is optional, the test can wait for it and handle a timeout when it does not appear.
try {
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(5)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
alert.sendKeys("Selenium");
alert.accept();
} catch (TimeoutException e) {
System.out.println(
"Prompt did not appear."
);
}
For a mandatory prompt, the test should normally report a failure rather than silently continue.
31. Prompt Alert After Button Click
driver.findElement(
By.id("enterName")
).click();
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertEquals(
alert.getText(),
"Enter your name"
);
alert.sendKeys("Manish");
alert.accept();
32. Prompt Alert After Form Action
driver.findElement(
By.id("continueButton")
).click();
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
String message = alert.getText();
Assert.assertTrue(
message.contains("Enter")
);
alert.sendKeys("Employee123");
alert.accept();
33. Prompt Alert for Employee ID
Consider an employee application that asks for an employee ID through a prompt.
driver.findElement(
By.id("employeeButton")
).click();
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertEquals(
alert.getText(),
"Enter Employee ID"
);
alert.sendKeys("EMP1001");
alert.accept();
34. Prompt Alert for User Name
driver.findElement(
By.id("nameButton")
).click();
Alert alert = driver.switchTo().alert();
Assert.assertEquals(
alert.getText(),
"What is your name?"
);
alert.sendKeys("Manish");
alert.accept();
35. Prompt Alert for Search Keyword
driver.findElement(
By.id("searchPrompt")
).click();
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
alert.sendKeys("Selenium WebDriver");
alert.accept();
Assert.assertTrue(
driver.getCurrentUrl()
.contains("search")
);
36. Prompt Alert for Product Quantity
driver.findElement(
By.id("quantityButton")
).click();
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
alert.sendKeys("5");
alert.accept();
String quantity =
driver.findElement(
By.id("quantityResult")
).getText();
Assert.assertEquals(
quantity,
"5"
);
37. Prompt Alert and Data Validation
Prompt input should be validated when the application expects a particular type or format of value.
String employeeId = "EMP1001";
alert.sendKeys(employeeId);
alert.accept();
String result =
driver.findElement(
By.id("employeeIdResult")
).getText();
Assert.assertEquals(
result,
employeeId
);
38. Prompt Alert with Dynamic Message
Prompt messages can contain dynamic information. In such cases, partial text validation may be more appropriate than exact matching.
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
String message = alert.getText();
Assert.assertTrue(
message.contains("Enter")
);
alert.sendKeys("Selenium");
alert.accept();
39. Prompt Alert with Multiple Inputs
An application can display multiple prompts sequentially. Selenium should handle each prompt before proceeding to the next one.
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert1 = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertEquals(
alert1.getText(),
"Enter first value"
);
alert1.sendKeys("First");
alert1.accept();
Alert alert2 = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertEquals(
alert2.getText(),
"Enter second value"
);
alert2.sendKeys("Second");
alert2.accept();
40. Multiple Prompt Alert Flow
Button Click
↓
Prompt 1
↓
sendKeys("First")
↓
accept()
↓
Prompt 2
↓
sendKeys("Second")
↓
accept()
↓
Verify Final Result
41. Prompt Alert vs HTML Input Field
| Prompt Alert | HTML Input Field |
| Native browser dialog. | Page DOM element. |
Handled using Alert. | Handled using WebElement. |
Access using switchTo().alert(). | Access using findElement(). |
Use alert.sendKeys(). | Use element.sendKeys(). |
Use alert.accept() or alert.dismiss(). | Usually click an HTML button. |
42. Common Mistake: Treating Prompt as WebElement
A native JavaScript prompt should not normally be handled as a normal HTML input element.
// Incorrect approach for a native prompt
WebElement input =
driver.findElement(
By.id("promptInput")
);
input.sendKeys("Selenium");
Correct approach:
Alert alert =
driver.switchTo().alert();
alert.sendKeys("Selenium");
alert.accept();
43. Common Mistake: Using driver.sendKeys()
The input operation belongs to the alert object when interacting with a native prompt.
// Incorrect
driver.sendKeys("Selenium");
Correct:
Alert alert =
driver.switchTo().alert();
alert.sendKeys("Selenium");
44. Common Mistake: Using driver.accept()
// Incorrect
driver.accept();
Correct:
Alert alert =
driver.switchTo().alert();
alert.accept();
45. Common Mistake: Using getText() on WebDriver
// Incorrect
String text = driver.getText();
Correct:
Alert alert =
driver.switchTo().alert();
String text =
alert.getText();
46. Common Mistake: Using XPath for a Prompt
A native prompt is not handled through normal page locators.
// Incorrect for a native JavaScript prompt
driver.findElement(
By.xpath("//input[@id='prompt']")
).sendKeys("Selenium");
Correct:
Alert alert =
driver.switchTo().alert();
alert.sendKeys("Selenium");
47. Prompt Alert vs HTML Modal
A prompt alert should be distinguished from an HTML/CSS modal that visually resembles a browser popup.
| Native Prompt | HTML Modal |
Created using JavaScript prompt(). | Created using HTML/CSS/JavaScript. |
Handled using Alert. | Handled using WebElement. |
Use switchTo().alert(). | Use normal locators. |
Use sendKeys() on Alert. | Use sendKeys() on the HTML input. |
Use accept()/dismiss(). | Click the HTML buttons. |
48. Prompt Alert and Browser Window
A prompt is also different from a new browser tab or window.
| Situation | Selenium Approach |
| JavaScript Prompt | driver.switchTo().alert() |
| New Browser Tab | driver.switchTo().window() |
| HTML Modal | driver.findElement() |
| Iframe | driver.switchTo().frame() |
49. Prompt Alert Synchronization
Synchronization is important when a prompt is displayed after a delay.
Click Action
↓
JavaScript Processing
↓
Prompt Appears
↓
alertIsPresent()
↓
switchTo().alert()
↓
getText()
↓
sendKeys()
↓
accept()
↓
Verify Result
50. Prompt Alert and Application State
After accepting or dismissing a prompt, the test should verify what happened in the application.
After Accept
Prompt
↓
Enter Value
↓
Accept
↓
Application Processes Value
↓
Verify Result
After Cancel
Prompt
↓
Dismiss
↓
Value Not Submitted
↓
Verify Cancel Behavior
51. Prompt Alert Utility Method
In a reusable automation framework, common prompt operations can be placed in utility methods.
public void enterPromptAndAccept(
WebDriver driver,
String value) {
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
alert.sendKeys(value);
alert.accept();
}
52. Prompt Alert Text Utility
public String getPromptText(
WebDriver driver) {
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
return alert.getText();
}
53. Prompt Alert Dismiss Utility
public void dismissPrompt(
WebDriver driver) {
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
alert.dismiss();
}
54. Using Prompt Utility
driver.findElement(
By.id("promptButton")
).click();
String message =
getPromptText(driver);
Assert.assertTrue(
message.contains("Enter")
);
enterPromptAndAccept(
driver,
"Selenium"
);
55. Prompt Alerts with Page Object Model
In a Page Object Model framework, the page object can contain the action that triggers the prompt while the alert handling can be centralized in an alert utility.
public class UserPage {
private WebDriver driver;
private By enterNameButton =
By.id("enterName");
public UserPage(WebDriver driver) {
this.driver = driver;
}
public void clickEnterName() {
driver.findElement(
enterNameButton
).click();
}
}
Test:
UserPage userPage =
new UserPage(driver);
userPage.clickEnterName();
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertEquals(
alert.getText(),
"Enter your name"
);
alert.sendKeys("Manish");
alert.accept();
56. Prompt Alert Test Framework Structure
Automation Framework
|
+-- Page Objects
|
+-- Test Classes
|
+-- Alert Utility
| |
| +-- waitForAlert()
| +-- getPromptText()
| +-- enterPrompt()
| +-- acceptPrompt()
| +-- dismissPrompt()
|
+-- Wait Utility
|
+-- Assertions
|
+-- Reports
57. Prompt Alert Logging
Logging prompt messages and entered test values can make automation debugging easier.
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
String message =
alert.getText();
System.out.println(
"Prompt Message: " + message
);
String value = "Selenium";
System.out.println(
"Entering Value: " + value
);
alert.sendKeys(value);
alert.accept();
58. Prompt Alert Data-Driven Testing
Prompt input can be tested with multiple values using a data-driven testing approach.
String[] names = {
"Manish",
"Rahul",
"Amit",
"Priya"
};
for (String name : names) {
driver.findElement(
By.id("promptButton")
).click();
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
alert.sendKeys(name);
alert.accept();
String result =
driver.findElement(
By.id("result")
).getText();
Assert.assertEquals(
result,
name
);
}
59. Prompt Alert Regression Testing
Prompt-related functionality should be included in regression testing when the application depends on user input through JavaScript dialogs.
- Prompt appears after the expected action.
- Prompt message is correct.
- Input can be entered.
- OK submits the input.
- Cancel does not submit the input.
- Application processes the entered value correctly.
- Incorrect or unexpected prompt behavior is reported.
60. Prompt Alert Test Scenarios
| Test Case | Expected Result |
| Prompt appears | Prompt becomes available. |
| Verify prompt text | Expected message is displayed. |
| Enter valid value | Value is entered successfully. |
| Accept prompt | Value is submitted. |
| Dismiss prompt | Value is not submitted. |
| Verify application result | Expected result is displayed. |
| Prompt missing | Test reports the expected behavior failure. |
| Wrong prompt message | Text validation fails. |
61. Prompt Alert Best Practices
- Use Selenium's
Alert interface for native JavaScript prompts.
- Use
driver.switchTo().alert() before interacting with the prompt.
- Use
getText() to validate the prompt message.
- Use
sendKeys() to enter prompt input.
- Use
accept() to submit the prompt.
- Use
dismiss() to cancel the prompt.
- Use
ExpectedConditions.alertIsPresent() when the prompt appears dynamically.
- Test both OK and Cancel scenarios.
- Verify the application state after prompt interaction.
- Use reusable alert utilities in larger automation frameworks.
- Do not confuse a native prompt with an HTML modal.
- Avoid unnecessary fixed waits.
62. Common Prompt Alert Mistakes
| Mistake | Correct Approach |
| Using XPath for a native prompt | Use switchTo().alert(). |
Using driver.sendKeys() | Use alert.sendKeys(). |
Using driver.accept() | Use alert.accept(). |
Using driver.getText() | Use alert.getText(). |
| Only testing OK | Also test Cancel using dismiss(). |
| No synchronization | Use alertIsPresent() when necessary. |
| Not validating the result | Verify the application's final state. |
| Using Alert API for HTML modal | Use WebElement locators for DOM-based modals. |
63. Mini Project: User Registration Prompt
Consider a simple application that asks the user for a name through a JavaScript prompt and then displays the entered name on the page.
Application Flow
Open Application
↓
Click Enter Name
↓
Prompt Appears
↓
"Enter your name"
↓
Enter "Manish"
↓
Click OK
↓
Application Displays Name
↓
Verify Name
64. Mini Project: User Registration Test
import java.time.Duration;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.Test;
public class UserPromptTest {
@Test
public void verifyUserPrompt() {
WebDriver driver = new ChromeDriver();
try {
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
driver.get(
"https://example.com"
);
driver.findElement(
By.id("enterName")
).click();
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertEquals(
alert.getText(),
"Enter your name"
);
String name = "Manish";
alert.sendKeys(name);
alert.accept();
String result =
driver.findElement(
By.id("result")
).getText();
Assert.assertEquals(
result,
name
);
} finally {
driver.quit();
}
}
}
65. Mini Project: Prompt Cancel Test
@Test
public void verifyPromptCancel() {
WebDriver driver = new ChromeDriver();
try {
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
driver.get(
"https://example.com"
);
driver.findElement(
By.id("enterName")
).click();
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertEquals(
alert.getText(),
"Enter your name"
);
alert.dismiss();
Assert.assertTrue(
driver.findElement(
By.id("promptCancelled")
).isDisplayed()
);
} finally {
driver.quit();
}
}
66. Prompt Alert Exception Reporting
try {
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
Assert.assertEquals(
alert.getText(),
"Enter your name"
);
alert.sendKeys("Selenium");
alert.accept();
} catch (TimeoutException e) {
Assert.fail(
"Expected prompt alert did not appear."
);
}
67. Prompt Alert and unhandledPromptBehavior
WebDriver sessions also have an unhandledPromptBehavior capability that controls how an unhandled user prompt is treated. Possible behavior settings can include accepting, dismissing, notifying, or ignoring an unhandled prompt.
For a prompt that is an expected part of a test case, explicitly interacting with the alert is usually clearer because the test specifies the expected input and user action.
68. Prompt Alert and Native Browser Context
Native JavaScript prompts are browser-controlled dialogs. They are different from ordinary HTML elements on the page and are therefore handled through Selenium's alert API.
Alert alert =
driver.switchTo().alert();
alert.getText();
alert.sendKeys("Selenium");
alert.accept();
69. Prompt Alert Quick Revision
| Requirement | Selenium Java Code |
| Switch to prompt | driver.switchTo().alert() |
| Read prompt message | alert.getText() |
| Enter value | alert.sendKeys("value") |
| Click OK | alert.accept() |
| Click Cancel | alert.dismiss() |
| Wait for prompt | ExpectedConditions.alertIsPresent() |
| No prompt available | NoAlertPresentException |
70. Prompt Alert Cheat Sheet
// Trigger Prompt
driver.findElement(
By.id("promptButton")
).click();
// Wait for Prompt
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
Alert alert = wait.until(
ExpectedConditions.alertIsPresent()
);
// Read Prompt
String message =
alert.getText();
// Validate
Assert.assertEquals(
message,
"Enter your name"
);
// Enter Text
alert.sendKeys("Manish");
// Accept
alert.accept();
// Or Cancel
// alert.dismiss();
71. Prompt Alert Learning Sequence
- Understand JavaScript
prompt().
- Understand the difference between alert, confirm, and prompt.
- Learn Selenium's
Alert interface.
- Learn
switchTo().alert().
- Learn
getText().
- Learn
sendKeys().
- Learn
accept().
- Learn
dismiss().
- Learn explicit waits.
- Learn
alertIsPresent().
- Automate prompt input.
- Automate prompt cancellation.
- Validate the application result.
- Create reusable prompt utilities.
- Integrate prompt handling into a Selenium framework.
72. Interview Question: What is a Prompt Alert?
A Prompt Alert is a native JavaScript dialog that displays a message and provides a text input field so that the user can enter a response. It normally provides OK and Cancel actions.
73. Interview Question: Which JavaScript Function Creates a Prompt?
prompt("Enter your name");
The JavaScript prompt() function creates a prompt dialog.
74. Interview Question: How Do You Handle a Prompt in Selenium?
Alert alert =
driver.switchTo().alert();
alert.sendKeys("Selenium");
alert.accept();
75. Interview Question: How Do You Enter Text into a Prompt?
Use the Alert object's sendKeys() method.
Alert alert =
driver.switchTo().alert();
alert.sendKeys("Selenium");
76. Interview Question: How Do You Cancel a Prompt?
Alert alert =
driver.switchTo().alert();
alert.dismiss();
77. Interview Question: How Do You Read Prompt Text?
Alert alert =
driver.switchTo().alert();
String text =
alert.getText();
78. Interview Question: Can XPath Locate a Native Prompt?
No. A native JavaScript prompt is handled through the Selenium Alert API rather than a normal XPath or CSS locator.
79. Interview Question: What is the Difference Between sendKeys() on Alert and WebElement?
| Method | Used For |
alert.sendKeys() | Entering text into a native JavaScript prompt. |
element.sendKeys() | Entering text into a DOM input or other keyboard-interactable element. |
80. Interview Question: Why Use alertIsPresent()?
alertIsPresent() waits for the native browser alert to become available before the test attempts to interact with it. This is useful when the prompt appears asynchronously or after JavaScript processing.
81. Interview Question: What Happens if a Prompt is Not Present?
If Selenium attempts to access an alert when none is displayed, an alert-related no-alert condition can occur. In Java automation, NoAlertPresentException can be handled when appropriate.
82. Interview Question: Can a Prompt be Dismissed After Entering Text?
Yes. Selenium can enter text into the prompt and then call dismiss(). The prompt is cancelled and the entered response is not submitted through the prompt.
Alert alert =
driver.switchTo().alert();
alert.sendKeys("Selenium");
alert.dismiss();
83. Interview Question: Can Prompt Alerts Have Default Values?
Yes. JavaScript's prompt() function can receive an initial value. Selenium can then replace that response value using sendKeys().
84. Interview Question: Can Multiple Prompts be Automated?
Yes. Selenium can handle sequential prompts one at a time. The first prompt should be handled before switching to the next displayed prompt.
Alert alert1 = wait.until(
ExpectedConditions.alertIsPresent()
);
alert1.sendKeys("First");
alert1.accept();
Alert alert2 = wait.until(
ExpectedConditions.alertIsPresent()
);
alert2.sendKeys("Second");
alert2.accept();
85. Prompt Alert Best-Practice Checklist
- Confirm that the popup is a native JavaScript prompt.
- Identify the action that triggers the prompt.
- Wait for the prompt when its appearance is dynamic.
- Switch to the prompt using
driver.switchTo().alert().
- Read and validate the prompt message.
- Enter the required value using
sendKeys().
- Accept the prompt when testing the OK path.
- Dismiss the prompt when testing the Cancel path.
- Verify the application result.
- Handle missing prompts appropriately.
- Use reusable utility methods in large frameworks.
- Keep native prompt handling separate from HTML modal handling.
86. Complete Prompt Alert Flow
User Action
↓
Application Button
↓
prompt()
↓
Prompt Alert
↓
Wait for Alert
↓
switchTo().alert()
↓
getText()
↓
Validate Message
↓
Enter Input Value
↓
sendKeys(value)
↓
┌─────────────┐
↓ ↓
accept() dismiss()
↓ ↓
OK Cancel
↓ ↓
Submit Input Cancel Input
↓ ↓
Verify Result Verify Result
87. Prompt Alert Final Summary
A Prompt Alert is a native JavaScript dialog that allows an application to request text input from a user. It is commonly created with the prompt() function and normally contains a message, an input area, an OK button, and a Cancel button.
In Selenium WebDriver, prompt alerts are handled through the Alert interface. The standard workflow is to wait for the prompt when necessary, switch to it, read the message, enter a value using sendKeys(), and then use accept() or dismiss() depending on the scenario.
Prompt Appears
↓
switchTo().alert()
↓
getText()
↓
sendKeys("Selenium")
↓
accept() / dismiss()
↓
Verify Application State
The most important Selenium methods to remember are:
driver.switchTo().alert() – accesses the active prompt.
alert.getText() – retrieves the prompt message.
alert.sendKeys("value") – enters text into the prompt.
alert.accept() – selects OK.
alert.dismiss() – selects Cancel.
ExpectedConditions.alertIsPresent() – waits for a prompt to appear.
88. Selenium Training Resources
For detailed Selenium WebDriver training covering locators, waits, alerts, prompts, confirmations, TestNG, Page Object Model, automation frameworks, and practical testing, visit Selenium Training.
To explore the course through a demo session, visit Register for Course Demo.