Switch Windows

User activities on a web application may trigger one or more new popup windows in order to complete the operation, such as user clicks on Login button, and a new small window is popped up for user to input user name and password to login. To automate an scenario like that we need to switch control among several windows from one to other.

Webdriver provides methods getWindowHandles() to retrieve all the windows, and getWindowHandle() to get current window which is having mouse focus.

To switch among different windows:

1. Remember the current window so that later on we can switch back to it
2. Then click on something button or what ever to open the new window
3. Use driver.getWindowHandles() to get all the windows and switch to the new one using driver.switchTo().window(..)
4. Do whatever you need to do in the new window, then close it if you don’t need it any more
5. Switch back to the old window, whose handler name we remembered in step 1
// Store the current window handle
String winHandleBefore = driver.getWindowHandle();
// Perform the click operation that opens new window

// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){

// Perform the actions on new window

// Close the new window, if that window no more required

// Switch back to original browser (first window)

// Continue with original browser (first window)