Reputation: 29749
I want to detect whether an alert is popped up or not. Currently I am using the following code:
try {
Alert alert = webDriver.switchTo().alert();
// check if alert exists
// TODO find better way
alert.getText();
// alert handling
log().info("Alert detected: {}" + alert.getText());
alert.accept();
} catch (Exception e) {
}
The problem is that if there is no alert on the current state of the web page, it waits for a specific amount of time until the timeout is reached, then throws an exception and therefore the performance is really bad.
Is there a better way, maybe an alert event handler which I can use for dynamically occurring alerts?
Upvotes: 40
Views: 150971
Reputation: 37826
Write the following method:
public boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} // try
catch (Exception e) {
return false;
} // catch
}
Now, you can check whether alert is present or not by using the method written above as below:
if (isAlertPresent()) {
driver.switchTo().alert();
driver.switchTo().alert().accept();
driver.switchTo().defaultContent();
}
Upvotes: 16
Reputation: 125
Alert alert = driver.switchTo().alert(); alert.accept();
You can also decline the alert box:
Alert alert = driver.switchTo().alert(); alert().dismiss();
Upvotes: 3
Reputation: 21
try
{
//Handle the alert pop-up using seithTO alert statement
Alert alert = driver.switchTo().alert();
//Print alert is present
System.out.println("Alert is present");
//get the message which is present on pop-up
String message = alert.getText();
//print the pop-up message
System.out.println(message);
alert.sendKeys("");
//Click on OK button on pop-up
alert.accept();
}
catch (NoAlertPresentException e)
{
//if alert is not present print message
System.out.println("alert is not present");
}
Upvotes: 2
Reputation: 806
This is what worked for me using Explicit Wait from here WebDriver: Advanced Usage
public void checkAlert() {
try {
WebDriverWait wait = new WebDriverWait(driver, 2);
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
alert.accept();
} catch (Exception e) {
//exception handling
}
}
Upvotes: 79
Reputation: 2509
You could try
try{
if(webDriver.switchTo().alert() != null){
Alert alert = webDriver.switchTo().alert();
alert.getText();
//etc.
}
}catch(Exception e){}
If that doesn't work, you could try looping through all the window handles and see if the alert exists. I'm not sure if the alert opens as a new window using selenium.
for(String s: webDriver.getWindowHandles()){
//see if alert exists here.
}
Upvotes: 0