How to Accept Alert in Selenium: Simple Guide
To accept an alert in Selenium, switch to the alert using
driver.switchTo().alert() and then call accept() on it. This will click the OK button on the alert popup and allow your test to continue.Syntax
The basic syntax to accept an alert in Selenium is:
driver.switchTo().alert(): Switches the WebDriver focus to the alert popup.accept(): Clicks the OK button on the alert to accept it.
java
driver.switchTo().alert().accept();
Example
This example shows how to open a webpage that triggers an alert, switch to the alert, accept it, and then continue with the test.
java
import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class AcceptAlertExample { 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 button that triggers alert driver.findElement(By.xpath("//button[text()='Click for JS Alert']")).click(); // Switch to alert Alert alert = driver.switchTo().alert(); // Accept the alert alert.accept(); // Verify result text String result = driver.findElement(By.id("result")).getText(); System.out.println("Result text: " + result); driver.quit(); } }
Output
Result text: You successfully clicked an alert
Common Pitfalls
- Trying to accept an alert before it appears causes
NoAlertPresentException. - Not switching to the alert before calling
accept()will fail. - Ignoring alerts can block test execution.
Always wait or ensure the alert is present before accepting.
java
/* Wrong way: Not switching to alert */ driver.accept(); // This will cause error /* Right way: Switch then accept */ driver.switchTo().alert().accept();
Quick Reference
| Action | Code Snippet |
|---|---|
| Switch to alert | driver.switchTo().alert() |
| Accept alert | driver.switchTo().alert().accept() |
| Dismiss alert | driver.switchTo().alert().dismiss() |
| Get alert text | driver.switchTo().alert().getText() |
| Send keys to alert | driver.switchTo().alert().sendKeys("text") |
Key Takeaways
Always switch to the alert before accepting it using driver.switchTo().alert().
Use accept() to click OK on the alert and continue test execution.
Wait for the alert to appear to avoid NoAlertPresentException errors.
Ignoring alerts can block your Selenium tests from running smoothly.
Use dismiss() if you want to cancel the alert instead of accepting it.