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

My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning

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.

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

by Amod Mahajan time to read: 2 min
0
%d bloggers like this: