We use cookies to analyze site traffic and show personalized ads. You can accept all cookies or decline personalized advertising.
Learn more in our Privacy Policy.
Handle native JavaScript popup dialogs with Selenium WebDriver.
JavaScript can show three main types of native popups: Alert (message + OK), Confirm (message + OK/Cancel), and Prompt (input + OK/Cancel).
These are browser-native dialogs, not normal HTML elements. You cannot locate them with By.id or By.cssSelector. Instead, Selenium gives you the Alert interface.
driver.switchTo().alert(): Switches focus to the popup.getText(): Read the message.accept(): Press OK.dismiss(): Press Cancel.sendKeys("text"): Type into a prompt.accept().accept() or dismiss().sendKeys() then accept().switchTo().alert().Result:
No action yet
Click the buttons to trigger native popups, then handle them with Selenium!
123456789101112131415161718// Handle a simple alert
driver.findElement(By.id("alert-btn")).click();
Alert alert = driver.switchTo().alert();
System.out.println("Alert text: " + alert.getText());
alert.accept();
// Handle a confirm dialog (dismiss / Cancel)
driver.findElement(By.id("confirm-btn")).click();
Alert confirm = driver.switchTo().alert();
confirm.dismiss();
// Handle a prompt dialog (send text + OK)
driver.findElement(By.id("prompt-btn")).click();
Alert prompt = driver.switchTo().alert();
prompt.sendKeys("Selenium Student");
prompt.accept();
driver.quit();Alert object.Once a JS popup appears, the browser is "blocked". Most WebDriver calls will fail until you use switchTo().alert().
Don’t reuse an old Alert object after closing it—fetch a new one every time with switchTo().alert().
Assert both OK and Cancel flows. Real bugs often hide in the "Cancel" path that nobody automated.