The Issue

Many browser-based applications use multiple tabs and/or windows. Finding the one you want for a given test or tests can be tricky, especially when there are more than two. You can’t be sure the windows have been added to the Selenium browser driver array in the order you might expect, so using indexes could mislead. And sometimes more than one of the windows will have the same URL and/or title.

A Solution

Identify a unique text string for the window you want to activate.   Be sure that string does not appear on any other window you might have open.

Then loop through all the windows using the driver’s window_handles command to get an array of the handles.   The driver switch_to command requires a handle as its argument.

This will make the window containing the text the current browser window.  

Important: The text string you assign to target must exist only on the page you want.

You can make a more flexible method by adding a parameter for the attribute to query.

Example calls:

  • Switch to the window with text ‘This is the Window I Want’.

  • Switch to the window with title ‘I am the Window You Want’.

  • Switch to the window with URL containing ‘desired-window’.

You can return to the base window (the first one opened) by using

 

The Result

The switch_to_window() method provides a flexible way of finding and using the window you need in your Ruby Selenium Webdriver scripts.  It will work for virtually any situation where the application spawns additional windows or tabs.  Its primary usefulness is that it can be used when title or URL are not guaranteed to be unique, or the index of your desired window is not certain.  

For more information on window handling in Ruby and Selenium Webdriver see How To Switch Between Multiple Browser Windows Using Ruby & Selenium WebDriver.