WebDriver has provided decent 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.
Implementation of isAlertPresent is very simple, Following code shows how to check if alert is present or not and if present cancel it.
Implementation of isAlertPresent is very simple, Following code shows how to check if alert is present or not and if present cancel it.
/** * If Javascript Alert is present on the page cancels it. */ public void handleAlert(){ if(isAlertPresent()){ Alert alert = driver.switchTo().alert(); System.out.println(alert.getText()); alert.accept(); } } /** * * @return True if JavaScript Alert is present on the page otherwise false */ public boolean isAlertPresent(){ try{ driver.switchTo().alert(); return true; }catch(NoAlertPresentException ex){ return false; } }