Selenium Tips: Working with Multiple Windows

Posted Nov 11th, 2018

One common Selenium issue is dealing with popup windows. You might also want to create your own new windows to do something in a shared session. For example: To create a new account, the pop back to the original page to see that the javascript has updated to ‘see’ this new ‘friend’ appears on a friends list.

For multiple window tasks, Selenium IDE provides the following commands:

  • openWindow(url, windowId): Will open your new window
  • waitForPopup(windowId, timeout): Will wait for the window to be opened and loaded
  • selectwindow(windowId): Will focus on this windows and any future actions will act on it

We could, then create the above test using Selenium IDE to run on

open /
type q sauce labs
click btnG
waitForTextPresent Sauce Labs
openWindow /search?q=santiago santiago
waitForPopUp santiago 30000
selectWindow santiago
assertTitle santiago - Google Search
selectWindow null
assertTitle sauce labs - Google Search

However, the IDE won't be able to play back that test as written. Let’s look at some code that does the same thing with webdriver3, created in Java and capable of running on Sauce OnDemand.


      WebDriver driver = new; 

      // And now use this to visit Google
      driver.findElement("q")).sendKeys("sauce labs");

      ((JavascriptExecutor) driver).executeScript("'')");
      Set <String> handles = driver.getWindowHandles();
      String firstWindowHandle = driver.getWindowHandle();

      System.out.println("Page title is: " + driver.getTitle());

      String secondWindowHandle = handles.iterator().next();
      System.out.println("Page title is: " + driver.getTitle());


This slightly different code, expressed in java, opens the window and does the parallel work that you expected it to do. Best of all, the tip is available in git, along with all of the dependencies and the build and run scripts for linux and macintosh. Windows users may need to add a .bat extension or change the parameters slightly as expressed in the, which also contains links in case the dependencies become out of date.

Of course, you can think of webdriver as an API and write this in any language webdriver supports, like Ruby, C#, or node.js. The function names will be essentially the same, using the variable types and capitalization/underscore appropriate for the language. You can also use the selectWindowHandle() syntax to grab popup windows.

Did you find this tip useful? Need some help adapting this to your needs? Let us know in the comments! Until next time, happy testing!

Written by

Matthew Heusser