javaseleniumwebdriverwaitwindow-handlesexpected-condition

How to handle new window, which opened automatically in new tab?


My test code do thomething, then automatically opening new tab and in a new tab automatically opening new window (not a tab).

When I use this code: driver.getWindowHandles() it is returns 2 tab ID instead 3 tab ID.

enter image description here


Solution

  • If it's a new window to count the number of WindowHandles you need to induce WebDriverWait for numberOfWindowsToBe(2) and you can use the following code block:

    String mainWindowHandler = driver.getWindowHandle(); // store mainWindowHandler for future references
    //line of code that opens a new TAB / Window
    new WebDriverWait(driver, 5).until(ExpectedConditions.numberOfWindowsToBe(2));  //induce WebDriverWait
    Set<String> handles = driver.getWindowHandles(); 
    Iterator<String> iterator = handles.iterator(); 
    while (iterator.hasNext()) 
    { 
        String subWindowHandler = iterator.next(); 
        if (!mainWindowHandler.equalsIgnoreCase(subWindowHandler))
        {
            driver.switchTo().window(subWindowHandler);
        }
    }
    

    References

    You can find a couple of relevant detailed discussions in: