How to switch control from child window to parent window in selenium webdriver?

Use this code:

 // Get Parent window handle
 String winHandleBefore = _driver.getWindowHandle();
 for (String winHandle : _driver.getWindowHandles()) {
   // Switch to child window
   driver.switchTo().window(winHandle);
 }

// Do some operation on child window and get child window handle.
String winHandleAfter = driver.getWindowHandle();

//switch to child window of 1st child window.
for(String winChildHandle : _driver.getWindowHandles()) {
  // Switch to child window of the 1st child window.
  if(!winChildHandle.equals(winHandleBefore) 
  && !winChildHandle.equals(winHandleAfter)) {
    driver.switchTo().window(winChildHandle);
   }
 }

// Do some operation on child window of 1st child window.
// to close the child window of 1st child window.
driver.close();

// to close the child window.
driver.close();

// to switch to parent window.
driver.switchto.window(winHandleBefore);

Leave a Comment