When I click a button on a page (in IE browser), a new popup page opens. My attempts to get the window handle for this popup have failed. Here is my first attempt:
There are 2 things you need to do:
Change the security setting in IE browser:
Open IE browser, click on "Internet Options" => "Security" => tick "Enable Protected Mode" for "Internet", "Local intranet", "Trusted sites" and "Restricted sites".
This gives IE driver the capability to get control of the new window handle, so that when you call
driver.getWindowHandles();
or driver.getWindowHandles().size();
you will get all the handles including the original window and the new windows. To be more accurate, you just need to set the security setting for all 4 domains to be the same which means you can uncheck "Enable Protected Mode" for all 4 domains but it is discouraged obviously.
After you call driver.switchTo().window(windowName);
, you need to add ((JavascriptExecutor) driver).executeScript("window.focus();");
before the IE driver can perform any actions on the window.
This is because IE driver needs the window that it is working on to be at the foreground, this line helps the driver get the focus of the window so that it can perform any actions on window that you want.
The following is a complete sample:
String baseWin = driver.getWindowHandle();
//Some methods to open new window, e.g.
driver.findElementBy("home-button").click();
//loop through all open windows to find out the new window
for(String winHandle : driver.getWindowHandles()){
if(!winHandle.equals(baseWin)){
driver.switchTo().window(winHandle);
//your actions with the new window, e.g.
String newURL = driver.getCurrentUrl();
}
}
//switch back to the main window after your actions with the new window
driver.close();
driver.switchTo().window(baseWin);
//let the driver focus on the base window again to continue your testing
((JavascriptExecutor) driver).executeScript("window.focus();");