Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Set which we get in driver.getWindowhandles() retain order

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()
like image 374
A.J Avatar asked Nov 08 '22 17:11

A.J


1 Answers

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(...)) {
        ...
    }
}
like image 82
Florent B. Avatar answered Dec 10 '22 04:12

Florent B.