In Selenium how to handle a new window?

Viewed 10070

I am writing a selenium script to login and create new mail, send it and logout. But when I click on New mail button, it opens a new window. In selenium how I can handle this. I am new to selenium. Please explain in detail.

3 Answers

How to get Window Handle:
String handle = driver.getWindowHandle();
If there are multiple window gets opened when you click on any link,button etc... then to get "window Handle" of each window -
Set windowHandles = driver.getWindowHandles();

"getWindowHandles()" : method return window handle (unique id for each opened window) so that the return type is set. Because set will not contain duplicate elements so here getWindowHandles return unique id/window handles for each winodw and stored in Set.

How to switch to correct / appropriate window:
Basically there are two ways to switch to appropriate window.

  1. By using windowName driver.switchTo().window( "windowName" );
    OR
  2. To get current/parent/default window handle:

    String handle = driver.getWindowHandle();
    driver.switchTo().window( handle  );
    OR
    Set < String > windowHandles = driver.getWindowHandles();
    
    for(String handle : windowHandles )
     {
         driver.swicthTo().window( handle ); 
    }
    

Example of Handling Multiple Windows In Selenium

Related