Handle Multiple Windows using Selenium WebDriver

Let’s understand this by example: Sometime when we click on a link using Selenium Webdriver, it opens a new window. Selenium doesn’t know about this new window as it is still focusing on Main window. In order to perform actions on new window, we need to switch the selenium control to the new window.

How do we switch the Selenium control to New Window ?

Every web page has a unique Id and Selenium keeps track of all windows opened during current session. We will use those unique window Ids to switch the control to New Window.

Selenium has following inbuilt functions to get the window Ids.

getWindowHandle() – Returns the Id of Main Window on which selenium is currently focusing.

getWindowHandles() – Returns the Ids of all windows opened during current session.

Once we get the Id of New Window then we need to call switchTo() function to switch the control to the new window using following command:

driver.switchTo().window("{New/Tab Window Id}");

How to switch the Selenium Control back to Main Window ?

There are cases where user have to switch the control back to Main window after completing testing on tab window. In that case also, you have to use the switchTo() function to switch the control back to Main Window. You just need to pass the Id of Main window as parameter as shown below. After executing below command, you will be able to perform selenium actions on Main Window again.