Road to switch window in webdriver

In this post I am going to show you that how to switch windows in webdriver(selenium 2). Below are some circumstances where we need to some trick to switch window.

1. Suppose you have only two windows one is parent and other is child window (opened window), your new window and parent window has similar title.

In Java:
Set windows = driver.getWindowHandles();
Iterator iter = windows.iterator();                                    
String parented  = iter.next();
driver.switchTo().window(iter.next());

In C#
String parentId = driver.WindowHandles.FirstOrDefault();
String childId = driver.WindowHandles.LastOrDefault();
driver.SwitchTo().Window(childId );

In above example I store parent Id for further switch to parent window.

2. Suppose that you have multiple window and want to switch on a particular window by  using title. Below are the codes for that

In Java:
String parentID = driver.getWindowHandle();
Set windows = driver.getWindowHandles();
Iterator iterator = windows.iterator();
while(iterator.hasNext())  {
                    driver.switchTo().window(iterator.next());
                    if(driver.getTitle().trim().equals("Mytitle")) {
                                        break;
                    }
}

In C#
String parentId = driver.CurrentWindowHandle;
foreach (var item in driver.WindowHandles)
{
      if(driver.SwitchTo().Window(item).Title.Equals(title))
       {
          driver.SwitchTo().Window(childId);
          break;
       }
 }
Hope this post is help you for switching windows in webdriver. 

No comments:

Post a Comment

Leave your comments, queries, suggestion I will try to provide solution