Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  • 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);
    
like image 836
Gurudatt Avatar asked Jan 31 '13 07:01

Gurudatt


People also ask

How do I switch from parent window to child window?

In order to switch its focus from the parent to the child window, we shall take the help of the switchTo(). window method and pass the window handle id of the child window as an argument to the method. Then to move from the child window to the parent window, we shall take the help of the switchTo().

Which statement will switch the control back to the main window?

once you select any option from the Alert window (say - YES/NO), the control automatically comes back to the parent or main window.


1 Answers

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);
like image 138
Manigandan Avatar answered Oct 14 '22 17:10

Manigandan