How to Dismiss Alert in Selenium: Simple Guide
To dismiss an alert in Selenium, switch to the alert using
driver.switchTo().alert() and then call dismiss() on it. This closes the alert without accepting it, similar to clicking the 'Cancel' button.Syntax
The syntax to dismiss an alert in Selenium involves two main steps:
driver.switchTo().alert(): Switches the WebDriver context to the alert popup.dismiss(): Closes the alert by clicking the 'Cancel' or equivalent button.
java
driver.switchTo().alert().dismiss();
Example
This example shows how to open a webpage that triggers an alert, switch to the alert, and dismiss it using Selenium WebDriver in Java.
java
import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class DismissAlertExample { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); driver.get("https://the-internet.herokuapp.com/javascript_alerts"); // Click the button that triggers the confirm alert driver.findElement(By.xpath("//button[text()='Click for JS Confirm']")).click(); // Switch to alert Alert alert = driver.switchTo().alert(); // Dismiss the alert (click Cancel) alert.dismiss(); // Verify the result text String result = driver.findElement(By.id("result")).getText(); System.out.println("Result after dismiss: " + result); driver.quit(); } }
Output
Result after dismiss: You clicked: Cancel
Common Pitfalls
Common mistakes when dismissing alerts include:
- Not switching to the alert before calling
dismiss(), which causesNoAlertPresentException. - Trying to dismiss an alert that is not a confirm or prompt type (e.g., simple alert only has
accept()). - Not handling timing issues where the alert is not yet present, causing errors.
Always wait or check for alert presence before dismissing.
java
try { Alert alert = driver.switchTo().alert(); alert.dismiss(); } catch (org.openqa.selenium.NoAlertPresentException e) { System.out.println("No alert to dismiss."); }
Quick Reference
| Action | Code Snippet | Description |
|---|---|---|
| Switch to Alert | driver.switchTo().alert() | Focus WebDriver on the alert popup |
| Dismiss Alert | alert.dismiss() | Close alert by clicking Cancel or equivalent |
| Accept Alert | alert.accept() | Close alert by clicking OK or equivalent |
| Get Alert Text | alert.getText() | Retrieve text message from alert |
Key Takeaways
Always switch to the alert using driver.switchTo().alert() before dismissing.
Use dismiss() to close confirm or prompt alerts without accepting them.
Handle exceptions for cases when alerts are not present to avoid errors.
Wait for the alert to appear before interacting to prevent timing issues.
Dismiss is different from accept; dismiss simulates clicking Cancel.