Thursday 9 February 2017

SELENIUM: How to verify or Check whether alert is present or not?

 

How to verify or Check whether alert is present or not?:
-------------------------------------------------------------------------------------------------------------



WebDriver has provided a  API to handle JavaScript Alert, however there isn't any API present which lets you know if JavaScript Alert is present on page or not. And sometime we are not sure if Alert is present or not, if it is present then we need to cancel it.

Using AlertIsPresnt():

WebDriver driver=new FirefoxDriver(); 
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(50,TimeUnit.SECONDS);                  
driver.get("https://www.facebook.com");
driver.findElement(By.id("some_id")).click();                  
//checking  whether Alert is present or not,if present accept the alert.
WebDriverWait w=new WebDriverWait(driver, 20);
                   try{
                   w.until(ExpectedConditions.alertIsPresent());
                   Alert alrt=driver.switchTo().alert();
                   alrt.accept();
                   } 
                 catch(Exception e)
                   {
                             System.out.println("Alert is not present");
                   }
Using User defined method:

public boolean isAlertPresent(){
    try{
            Alert a=driver.switchTo().alert();
               return true;
    }
    catch (NoAlertPresentException e) {
        return false;
    }
}    

public void handleAlert(){
if(isAlertPresent()){
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
}
}

No comments:

Post a Comment