Make Selenium Easy

Does getWindowHandles() method return handles in the same order as windows launch?

Introduction

As part of the Selenium WebDriver – Java series, let’s learn how does getWindowHandles() work.

If multiple child windows are launched in an application due to some actions then Selenium WebDriver provides the capability to handle multiple windows. We can switch to any open window and perform actions. Selenium provides a method getWindowHandles() to get handles of all open windows. Do getWindowHandles() method return the window handles in the same order it was launched? Let’s find the answer by executing sample programs.

Prerequisite

I have used the below dependency of Selenium WebDriver – Java.

Example HTML code

I have created a webpage that opens “Google”, “Facebook” and “Flipkart” websites in a new tab.

You can find the HTML code below:-

Sample program

Let’s open the webpage of “Google” followed by “Facebook” and “Flipkart” and get window handles in a program below:-

Output

If you observe output carefully you will find that returned windows handles are not in the same order it was opened. The return type of getWindowHandles() method is a Set that does not maintain insertion order. But if you see the implementation of this method you will find that it returns an instance of LinkedHashSet which maintains insertion order. Due to this, I have seen many places people claim that insertion order is the order in which windows were opened. But it does not seem to be correct that you can see in the above example.

I have tried the same code in Firefox and output is same as Chrome.

You can download/clone the above sample project from here.

You can subscribe to my YouTube channel RetargetCommon to learn from video tutorials.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappyLearning

Find all Selenium related posts here, all API manual and automation related posts here, and find frequently asked Java Programs here.

Many other topics you can navigate through the menu.

Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.