linuxseleniumselenium-webdriverwebdriverwaitwindow-handles

org.openqa.selenium.WebDriverException: invalid argument: 'handle' must be a string while window handling with Selenium and Java in Linux


I have an requirement of running test cases in CI pipeline. where the VM is linux. Selenium multiple window handling - switchTo() method throws exception for linux platform.

Exception:

org.openqa.selenium.WebDriverException: invalid argument: 'handle' must be a string

Code trials:

driver.switchTo().window(subWindowHandler);

Its declared as per multiple window handle way:

String subWindowHandler = null; 
Set<String> handles = driver.getWindowHandles(); 
Iterator<String> iterator = handles.iterator(); 
while (iterator.hasNext()) { 
    subWindowHandler = iterator.next(); 
}

This code works perfectly in local windows system.


Solution

  • This error message...

    org.openqa.selenium.WebDriverException: invalid argument: 'handle' must be a string
    

    ...implies that the handle which was passed as an argument needs to be a string.

    Logically you are pretty close. Possibly the driver.getWindowHandles() is getting executed too early even before the second window handle is getting created/recognized.


    Solution

    As a solution 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);
        }
    }
    

    You can find a relevant detailed discussion in Best way to keep track and iterate through tabs and windows using WindowHandles using Selenium