If you have more then one browser (using java 8)
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TestLink {
private static Set<String> windows;
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("file:///C:/Users/radler/Desktop/myLink.html");
setWindows(driver);
driver.findElement(By.xpath("//body/a")).click();
// get new window
String newWindow = getWindow(driver);
driver.switchTo().window(newWindow);
// Perform the actions on new window
String text = driver.findElement(By.cssSelector(".active")).getText();
System.out.println(text);
driver.close();
// Switch back
driver.switchTo().window(windows.iterator().next());
driver.findElement(By.xpath("//body/a")).click();
}
private static void setWindows(WebDriver driver) {
windows = new HashSet<String>();
driver.getWindowHandles().stream().forEach(n -> windows.add(n));
}
private static String getWindow(WebDriver driver) {
List<String> newWindow = driver.getWindowHandles().stream()
.filter(n -> windows.contains(n) == false).collect(Collectors.toList());
System.out.println(newWindow.get(0));
return newWindow.get(0);
}
}