user3122524
user3122524

Reputation: 13

How to check if an alert is present and if yes then accept it

I have a situation where i want to check if there exists a popup, if yes then accept it otherwise move forward. Kindly help as I am new to selenium.I am using java. Thanks.

Upvotes: 0

Views: 11004

Answers (2)

Sumitbit2005
Sumitbit2005

Reputation: 333

I think this may you:

@Test
public void testAlertOk()
{
//Now we would click on AlertButton
WebElement button = driver.findElement(By.id("AlerButton"));
button.click();
try {
//Now once we hit AlertButton we get the alert
Alert alert = driver.switchTo().alert();
//Text displayed on Alert using getText() method of Alert class
String AlertText = alert.getText();
//accept() method of Alert Class is used for ok button
alert.accept();
//Verify Alert displayed correct message to user
assertEquals("this is alert box",AlertText);
} catch (Exception e) {
e.printStackTrace();
}
}

Source: Click here for more detail understanding

Upvotes: 0

newLearner
newLearner

Reputation: 184

It will be something like this.

WebDriverWait wait = new WebDriverWait(driver, 10 /*timeout in seconds*/);
                           if(wait.until(ExpectedConditions.alertIsPresent())==null){
                                 System.out.println("alert was not present");
                           }
                           else
                           {
                            Alert alert = driver.switchTo().alert();
                           alert.accept();
                           System.out.println("alert was present and accepted");
                           }

Upvotes: 2

Related Questions