Many a times, while testing web application, we face such situation where we need to handle javascript alert from our webdriver code in selenium.
And it is also very common that we get the below written UnhandledAlertException while running our code.
The code may look like-
Build info: version: ‘2.39.0’, revision: ‘ff23eac’, time: ‘2013-12-16 16:12:12’
System info: host: ‘HOST-ABCD’, ip: ‘10.56.23.2345, os.name: ‘Windows Server 2008 R2’, os.arch: ‘amd64’, os.version: ‘6.1’, java.version: ‘1.7.0_51’
Session ID: ad3746bf-4c03-4de9-9bb8-17831538c562
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{platform=WINDOWS, javascriptEnabled=true, elementScrollBehavior=0, ignoreZoomSetting=false, enablePersistentHover=true, ie.ensureCleanSession=false, browserName=internet explorer, enableElementCacheCleanup=true, unexpectedAlertBehaviour=dismiss, version=8, ie.usePerProcessProxy=false, cssSelectorsEnabled=true, ignoreProtectedModeSettings=false, requireWindowFocus=false, handlesAlerts=true, initialBrowserUrl=http://localhost:9493/, ie.forceCreateProcessApi=false, nativeEvents=true, browserAttachTimeout=0, ie.browserCommandLineSwitches=, takesScreenshot=true}]
The code we use to combat the alert box is given below:
driver.switchTo().alert().accept();
Let us understand why this exception comes then:
It is seen many a time the application is slow in nature and selenium is trying to execute the code before the alert pop up. So the next statement will have this exception. Many coder try to put a Thread.Sleep(5) before the above code. But the success rate to avoid this exception is upto the speed of application.
So how to resolve this issue?
Well instead of Thread.Sleep(5) use a more correct method..
WebDriverWait wait =new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.alertIsPresent());
driver.switchTo().alert().accept();
So this code will wait for the alert to come and then it will click on ok what accept button.
Problem might solve, but is this the correct solution??
Probably, No!!!.
This condition does not hold good for the case where the pop up do not appear. It will go to infinite loop. Let us make it little safe:
public boolean isAlertPresent(){
try{
driver.switchTo().alert();
return true;
}//try
catch(Exception e){
return false;
}//catch
}
and
if(isAlertPresent()){
driver.switchTo().alert();
driver.switchTo().alert().accept();
driver.switchTo().defaultContent();
}
There is one more beautiful way to solve this issue:
for(String s: webDriver.getWindowHandles()){
//see if alert exists here.
}