selenium: is the first window handle always the main window? selenium: is the first window handle always the main window? selenium selenium

selenium: is the first window handle always the main window?


According to the current WebDriver API Specification:

6.3 Iterating Over Windows

getWindowHandles

An array containing a window handle for every open window in this session. This array of returned strings must contain a handle for every window associated with the browser session and no others. For each returned window handle the javascript expression "window.top.closed" (or equivalent) must evaluate to false at the time the command is being executed.

The ordering of the array elements is not defined, but may be determined by iterating over each top level browser window and returning the tabs within that window before iterating over the tabs of the next top level browser window.

In short, no - there is no guaranteed order.


As alecxe pointed out the handles can be in any order.

I solve the issue of knowing which handle is the main window by saving the handle immediately after I point Selenium to the first page to load (at this point the list of handles contains only one handle, which is the main window), and I save this value for future use. Then when I scan the list of handles later, I compare with the value I saved and know that handles that don't match it are not the initial window.

Doing this is useful in "tear down" or "clean up" code between tests in a test suite if you have some tests that may open other windows. Using the method I describe here, your tear down code can be generic and not worry about whether any specific test is actually opening additional windows.