Search code examples
javaselenium-webdriver

Switch Between 3 Tabs Using Selenium WebDriver with Java


I'm trying to switch between three tabs using the Selenium getWindowHandles method and an iterator. It works well for two tabs, but when I add a third one, I encounter an error.

My goal is to start in Google.com, then switch to Facebook.com, then to StackOverflow.com, and finally switch back to Google.com. How can i fix this?

Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:758)
    at java.base/java.util.LinkedHashMap$LinkedKeyIterator.next(LinkedHashMap.java:778)
    at locators.SwitchWindowTab.main(SwitchWindowTab.java:29)

Solution

  • You're encountering a NoSuchElementException because the Iterator is exhausted before switching to the third tab. Instead, use a List to store getWindowHandles() and access tabs by index.

    You can refer the below code:

        WebDriver driver = new ChromeDriver();
        driver.get("https://www.google.com");
    
        // Open new tabs
        driver.switchTo().newWindow(WindowType.TAB).get("https://www.facebook.com");
        driver.switchTo().newWindow(WindowType.TAB).get("https://stackoverflow.com");
    
        // Store window handles in a list
        Set<String> handles = driver.getWindowHandles();
        List<String> tabs = new ArrayList<>(handles);
    
        // Switch between tabs using index
        driver.switchTo().window(tabs.get(1)); // Facebook
        driver.switchTo().window(tabs.get(2)); // StackOverflow
        driver.switchTo().window(tabs.get(0)); // Back to Google
    
        driver.quit();
    

    NOTE: If this code still doesn't work for you, please share your code so we can provide an exact and accurate solution.