Monday, 5 January 2015

Handling alerts

An alert box appears in scenarios such as , when we try to submit a form or when we try to delete a record.

For people who may get confused with handling alerts and popups, especially those who are new to webdriver, here's a tip : Alert has only buttons such as OK and Cancel. So that's how we identify an alert.

If we want to click ok, we implement the accept() method of the Alert interface. 

If we want to click cancel in an alert, we implement the dismiss() method of the Alert interface.

In the example below, we'll launch the website and click on the submit button at the bottom of the page. This triggers an alert, that has only one button - 'OK'. We click on it , and then the alert disappears.

public class AlertDemo {

public static void main(String[] args) {

WebDriver driver = new FirefoxDriver();

driver.navigate().to("https://www.tin-nsdl.com/customerfeedback.php");
driver.manage().window().maximize();

WebDriverWait wait = new WebDriverWait(driver, 20); //WebDriverWait - Interface
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.name("Submit")).click();
wait.until(ExpectedConditions.alertIsPresent());//ExpectedConditions - class
Alert alr = driver.switchTo().alert();//Alert - interface
alr.accept();
driver.quit();
}

}



Note:

In the above piece of code, we have used WebDriver wait, to make sure , the webdriver waits untill the alert appears.

If this is not done and if the driver.switchTo().alert() statement is executed before the alert actually opens , then there will be an exception : NoAlertPresentException



Pay It Forward...

Lots of energy ..

DR









No comments:

Post a Comment