Search code examples
javaseleniumselenium-webdriverautomationwindow-handles

Why am I unable to navigate into a new window with the Selenium Webdriver?


I am unable to navigate into a new window, as it is showing the same window for both parent and child. I use this code. What is the problem?

String parent_Window = driver.getWindowHandle();
Set<String> handles =  driver.getWindowHandles();
 for(String window_Handle  : handles){
    if(!window_Handle.equals(parent_Window)){
        driver.switchTo().window(window_Handle);
        //<!--Perform operation here for new window--> 

     driver.switchTo().window(parent_Window);
        }
    }

Solution

  • use the below code:

    // Store the current window handle
    String winHandleBefore = driver.getWindowHandle();
    
     // Switch to new window opened
    for(String winHandle : driver.getWindowHandles()){
    driver.switchTo().window(winHandle);
     }
    
    // Perform the actions on new window
    
    // Close the new window, if that window no more required
    driver.close();
    
     // Switch back to original browser (first window)
    driver.switchTo().window(winHandleBefore);