Introduction
Prompt alerts ask the user to enter text. Testing this ensures your app handles user input correctly.
Prompt alerts ask the user to enter text. Testing this ensures your app handles user input correctly.
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.
Alert alert = driver.switchTo().alert();
alert.sendKeys("Hello");
alert.accept();Alert alert = driver.switchTo().alert();
alert.sendKeys("12345");
alert.dismiss();This test opens a page with a prompt alert, enters text, accepts it, and prints the result message.
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(); } } }
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.
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.
Alert alert = driver.switchTo().alert();
alert.sendKeys("hello");
alert.accept();Alert alert = driver.switchTo().alert();
alert.sendKeys("test");
alert.dismiss();Pass the test and this pattern moves unknown