The Issue

There will be times when you will need to do some testing in one browser window/tab, open another, interact with elements on the new page, and return to the first. Additionally, you may be automating an interaction on a website that will only open its contents in a new window/tab, requiring you to switch over windows to proceed. Even if the window/tab is currently in view, your browser commands will not affect it. So how can we select which window to work within?

The Answer

We can use the command listed below to switch between multiple windows/tabs in a browser session:

In this case, the [0] at the end signifies the parent window, which will be the first browser window you opened. By switching the [0] to [1], the child window will be selected, allowing you to execute commands in it. This can continue with 2,3,4,etc., increasing the index by 1 for each additional browser window.

The Code

We’ll use the University of South Florida’s website, which will open a new tab as we navigate to the College of Arts and Sciences Page from the Colleges home page.


The Result

Lets save the file (MultipleWindows.rb) and run it from the command line. Here is a breakdown of the result:

  • Browser opens
  • Browser navigates to USF colleges homepage
  • Clicks on College of Arts and Sciences link
  • New tab opens
  • Switches to new tab, allowing us to execute commands on it
  • Clicks on Academic Programs link from new tab
  • Validates Academic Programs page

We will see the result in the command line, displaying a message confirming our header is validated:




Below is the error you would encounter if you did NOT switch the window.  

Capture37Essentially, the script was not able to click the link “Academic Programs” since the focus was still on the Parent Window (Index 0) and the “Academic Programs” link is present in the Child Window (Index 1)

The Takeaway

Switching between browser windows using Ruby, Selenium and Watir WebDriver can get tricky for applications that spawn multiple windows.  The key is ensuring that you can keep track of the hierarchy of the Parent Child Windows and ensuring that you use the correct index number for the window you’re trying to interact with.