How to switch control from child window to parent window in selenium webdriver?
selenium, selenium-webdriver
Solution
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);
Problem
- From Parent window I'm passing the control to child window - I'm performing actions in the child window - After performing, from a child window one more window will open(Child of 1st child window). I have to close both the child windows and have to get back to the Parent window. I'm not able to switch the control from child to parent window. I have tried out the below code ``` String winHandleBefore = _driver.getWindowHandle(); for(String winHandle : _driver.getWindowHandles()){ _driver.switchTo().window(winHandle); } String winHandleAfter = _driver.getWindowHandle(); ``` /performing actions in the child window/ ``` driver.close(); _driver.switchTo().window(winHandleBefore); ```