How to switch between browser windows

Often websites have links that open in new windows, tabs of pop-ups. This article shows how to manage the opened windows with the RPA.Browser.Selenium to allow your robot to switch between them to accomplish its task.

As a demo, we will use this simple application:

Here we have two buttons: the first one opens a new window, the second one opens an alert. The window that gets opened has a button to close it.

Our robot will:

  • Click on the Open new window button.
  • Switch to the window that gets opened.
  • Close it by clicking on the button.
  • Go back to the first window and click on the Open an alert button.

Robot Script

*** Settings *** Documentation An example of working with multiple browser windows. Library RPA.Browser.Selenium *** Tasks *** Navigate to app, open new windows, close it, click on alert button Open Available Browser https://gxd4e.csb.app/ Click Button When Visible id:openwindow Switch Window new Click Button When Visible id:closewindow Switch Window main Click Button When Visible id:openalert

When a new window is opened by clicking on the Open new window button, we can use the Switch Window keyword provided by the RPA.Browser.Selenium library to switch to it. We can pass new as an argument to the keyword, and the robot will switch to the newly opened window. When we want to go back to the previous window, we can call the keyword again, passing it main as the argument.

Here's our robot at work:

Robot switching windows

Alternative approach: using window handles

We can achieve the same result by using "window handles", the internal names that the browser assigns to its windows:

*** Settings *** Documentation An example of working with multiple browser windows. Library RPA.Browser.Selenium *** Tasks *** Navigate to app, open new windows, close it, click on alert button Open Available Browser https://gxd4e.csb.app/ Click Button When Visible id:openwindow ${handles}= Get Window Handles Switch Window ${handles}[1] Click Button When Visible id:closewindow Switch Window ${handles}[0] Click Button When Visible id:openalert

In this version of the script, we use the Get Window Handles keyword to get back a list of all the defined handles, and store them in a variable:

List of window handles in the log

We can then use the handles as arguments in our script by accessing the items in the list (note that the count starts from zero):

For example, this code: Switch Window ${handles}[1] will switch the robot to the second defined window.

Last edit: May 5, 2022