I have a confusion whether the set which return windows handles in selenium retain order in which windows are opened, I mean like first window will be at first position, next window opened at next position and so on.
This is the code:
Set<String> handles = driver.getWindowhandles()
It depends on the driver you are using. Some keep the order and some don't. The WebDriver protocol says that the order is arbitrary:
The Get Window Handles command returns a list of window handles for every open top-level browsing context. The order in which the window handles are returned is arbitrary.
This is probably why all the handles are placed in a Set
to prevent you form accessing an handle by index.
If you only have 2 windows then simply switch to the one which is not the current window :
Set<String> handles = driver.getWindowHandles();
handles.remove(driver.getWindowHandle());
driver.switchTo().window(handles.iterator().next());
But if you have more than 2 windows, then keep track of each new window or iterate over each window until you get the expected one:
Set<String> handles = driver.getWindowHandles();
handles.remove(driver.getWindowHandle());
for (String hwnd : handles) {
driver.switchTo().window(hwnd);
if (driver.getCurrentUrl().contains(...)) {
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With