Selenium 2: Open link in new tab and close tabs

Alp picture Alp · May 17, 2011 · Viewed 42.1k times · Source

I want to be able to open a link in a new tab in Selenium 2. Also i want to close the tab when i am finished interacting with the page. How is this possible if I have a WebElement of an <a> tag?

I am using the Java API of Selenium 2 with the Firefox Driver, running on Firefox 4.

Answer

Henry picture Henry · Apr 24, 2012

The way I figure out for selenium 2, work fine for Chrome and firefox, IE has security check issue:

Set<String> winSet = webDriver.getWindowHandles();
List<String> winList = new ArrayList<String>(winSet);
String newTab = winList.get(winList.size() - 1);
webDriver.close(); // close the original tab
webDriver.switchTo().window(newTab); // switch to new tab