Skip to content
Advertisement

I am not able to traverse to parent window to child window

Below code i was used in Selenium Eclipse, But i get a error shown in this line “String childid = it.next();” I am unable to traverse parent window to child window

import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class HandleMultipleWindows {

    public static void main(String[] args) {
          
    System.setProperty("webdriver.chrome.driver","C:\Users\vinay\Desktop\driver\chromedriver.exe");

        WebDriver driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        driver.get("https://accounts.google.com/signin");

        System.out.println("Before switching");
        System.out.println(driver.getTitle());
        driver.findElement(By.xpath("//*[text()='Learn more']")).click();
        
        Set<String> ids =driver.getWindowHandles();
        Iterator<String> it = ids.iterator();
        String parentid = it.next();
        String childid = it.next();
        driver.switchTo().window(childid);
        System.out.println("After switching");
        System.out.println(driver.getTitle());
        
        driver.switchTo().window(parentid);
        System.out.println("Switch back to parent id");
        System.out.println(driver.getTitle());
        
        
    }

}

Advertisement

Answer

You should get Parent window in a right way:

public static void main(String[] args) {
      
System.setProperty("webdriver.chrome.driver","C:\Users\vinay\Desktop\driver\chromedriver.exe");

    WebDriver driver = new ChromeDriver();
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    driver.get("https://accounts.google.com/signin");

    System.out.println("Before switching");
    System.out.println(driver.getTitle());
    driver.findElement(By.xpath("//*[text()='Learn more']")).click();
    
    String parentid =driver.getWindowHandle();

    Set<String> ids =driver.getWindowHandles();
            
    Iterator<String> it= ids.iterator();
    //Here you can iterate using Iterator if you have more than one child, but once you have only one you can still use next once

    String childid =it.next();  

    driver.switchTo().window(childid);
    System.out.println("After switching");
    System.out.println(driver.getTitle());
    
    driver.switchTo().window(parentid);
    System.out.println("Switch back to parent id");
    System.out.println(driver.getTitle());
   }

 }
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement