Opening and Closing Tabs Using Selenium
In this post I reference methods in the Selenium C# client driver. Equivalent methods should exist in whichever other language client driver you use.
Some testing requires opening a new window, performing an action, then closing that window, perhaps even returning to the original window to continue the test. There are many, many ways of managing tabs in selenium, so lets take a look at what works and what doesn’t.
Tabs = Windows
First of all, Selenium really has no concept of what a tab is and how it differs from a window. Each WebDriver instance has a reference to it’s current window handler, which is points to the current tab or window that driver is interacting with. When managing tabs, we have to be able to create a window handler, switch to it, do some stuff, then switch back to our original window handler.
Switching Window Handlers
So now you have a new tab in your browser, but you still need to tell your WebDriver to switch to it, otherwise commands will continue to be sent to the original tab. This is actually pretty easy and is done using the
SwitchTo() command into which you pass the window handler that you want to switch to.
So putting everything together, here is what the code would look like to:
- Create a new tab
- Switch to it
- Do something in the new tab
- Close the new tab
- Switch back to our original tab
This approach works when executing tests both locally and remotely. Keep in mind that you can only execute a
window.close() on a tab that was initially opened using a
Actually JS window.close works fine when opening from a web app :
final Set set1 = driver.getWindowHandles();
final Iterator win1 = set1.iterator();
final String parent = win1.next();
final String child = win1.next();
“https://someUrl” + trackingNumber));