Search code examples
javaseleniumselenium-webdriverwindow-handles

Printing title of third window in selenium webdriver using java


My Scenario is:

I have base URL: www.****.com

After opening the URL, I am clicking a link called, "Test", it will open another window say "B", In window B I am clicking on button "button1", it will open another window "C". I have to get the title of window C.

Below is my sample code:

    driver.get("http://www.****.com/");
    WebElement menu_ele        =driver.findElement(By.tagName("a").linkText("PRACTICE"));
    Actions act = new Actions(driver);
    act.moveToElement(menu_ele).build().perform();
    Thread.sleep(1000);
    driver.findElement(By.tagName("a").linkText("Demo Sites")).click();
    driver.findElement(By.tagName("a").linkText("http://www.****.com/Practiceform/")).click();
    Set<String> window = driver.getWindowHandles();
    String window1 = (String) window.toArray()[0];
    String window2 = (String) window.toArray()[1];
   // String window3 = (String) window.toArray()[2];
    driver.switchTo().window(window2);
    driver.findElement(By.id("button1")).click();
    Set<String> win = driver.getWindowHandles();
    String window3 = (String) window.toArray()[0];
    driver.switchTo().window(window3);
    System.out.println(driver.getTitle());
    driver.manage().window().maximize();

I am unable to switch to window C. I know this is not a best practice, suggest some ways to achieve it.


Solution

  • In your code, I see you are trying to switch to window3 but you are assigning it to the first window by using String window3 = (String) window.toArray()[0];

    Use

    String window3 = (String) window.toArray()[2];
    

    instead.

    Your Edited Code

        Set<String> window = driver.getWindowHandles();
        String window1 = (String) window.toArray()[0];
        String window2 = (String) window.toArray()[1];
       // String window3 = (String) window.toArray()[2];
        driver.switchTo().window(window2);
        driver.findElement(By.id("button1")).click();
        Set<String> win = driver.getWindowHandles();
        String window3 = (String) window.toArray()[2]; //get the third window from the set
        driver.switchTo().window(window3);
        System.out.println(driver.getTitle());
        driver.manage().window().maximize();