Window Handles Using Selenium

Set<String> window1= driver.getWindowHandles();
Object s[]=window1.toArray();

2nd Example :-

String parentwindow = driver.getWindowHandle(); // get the current window handle

driver.findElement(By.xpath("//*[@id='someXpath']")).click(); // click some link that opens a new window

for (String winHandle : driver.getWindowHandles()) {

    driver.switchTo().window(winHandle); // switch focus of WebDriver to the next found window handle (that's your newly opened window)


//code to do something on new window

driver.close(); // close newly opened window when done with it

driver.switchTo().window(parentwindow); // switch back to the original window


3rd Example :-


// Get and store both window handles in array

  Set<String> Allwindows = driver.getWindowHandles();

// Extract parent and child window handle from all window handles

  String window1 = (String) Allwindows.toArray()[0];

  System.out.print("window1 handle code = "+Allwindows.toArray()[0]);

  String window2 = (String) Allwindows.toArray()[1];

  System.out.print("newwindow2 handle code = "+Allwindows.toArray()[1]);

  //Switch to window2(child window) and performing actions on it.