I hope this day finds you well.
I'm working on an automation suite and I've run into an annoying problem when it comes to switching windows. I have a script which clicks a button which opens in a new window. I'm able to switch to that new window but only intermittently. Here's my code:
mainWindowHandle = driver.getWindowHandle();
objAdminPage.clickButtonForNewWindow();
Set<String> handles = driver.getWindowHandles();
System.out.println(handles);
System.out.println("This is the main handle " + mainWindowHandle);
for(String winHandle : handles){
System.out.println("In the loop " + handles);
if(!winHandle.equals(mainWindowHandle)){
driver.switchTo().window(winHandle);
System.out.println(winHandle);
}
}
This seems to be the standard way of doing things. The script saves the current window handle, then gets all handles, loops over them until it finds the one which isn't the current window and the driver switches to it. And this works.....sort of. Often when I run the script it won't switch to the new window, leading to failed tests and badness. I've scattered sysouts through the code as you can see and I've noticed that on failure I'm only getting one handle in the handles set, not both. What seems to be happening is that the system is charging ahead and the set is being created before Selenium can get both handles.
I'm able to get this to run reliably if I make a Thread.sleep(1000) call prior to creating the set but I really don't like having to do this. It seems inelegant and I've not seen this being necessary elsewhere. If anyone has any better solutions or knows why I'm having to hack the system like this I would greatly appreciate it.
Running Selenium 2.45.0 MacOS 10.9.