1
votes

I am trying to switch between two tabs and found following code

 ArrayList<String> tabs2 = new ArrayList<String> (page.getWindowHandles());
     System.out.println(tabs2.size());
        page.switchTo().window(tabs2.get(1));
        page.close();
        page.switchTo().window(tabs2.get(0));

I have one doubt in this. My window is same so page.getWindowHandles() is returning only one handle. tabs2.size is 1 so page.switchTo().window(tabs2.get(1)); is giving exception ArrayIndexOutOfBound

I found similar code in this post switch tabs using Selenium WebDriver with Java but for me this code is giving exception.

2
whats the issue here? If you have only 1 tab you are already there on that tab ... and tabs2.size() is returning 1 that is correct. - Paras
I opened two tabs then I am using this code still it's returning 1. then how to work on two tabs? - sajid
do you open second tab using selenium or manually or it is application behavior? - Andersson
I used this code page.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t"); - sajid

2 Answers

0
votes

Just try and add a line of code to ensure there are two or more tabs open in the browser :

page.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");

Note that the actual keys to send depend on your OS, for example, Mac uses Keys.COMMAND + t, instead of Keys.CONTROL + t.

Post this, the piece of code used by you seems appropriate to switch tabs :

ArrayList<String> tabs2 = new ArrayList<String> (page.getWindowHandles());
System.out.println(tabs2.size());
page.switchTo().window(tabs2.get(1));
page.close();
page.switchTo().window(tabs2.get(0));

Note : I am assuming the page here is the WebDriver instance itself.

0
votes
protected void switchTabsUsingPartOfUrl(String platform) {
        String currentHandle = null;
        try {
            final Set<String> handles = driver.getWindowHandles();
            if (handles.size() > 1) {
                currentHandle = driver.getWindowHandle();
            }
            if (currentHandle != null) {
                for (final String handle : handles) {
                    driver.switchTo().window(handle);
                    if (currentUrl().contains(platform) && !currentHandle.equals(handle)) {
                        break;
                    }
                }
            } else {
                for (final String handle : handles) {
                    driver.switchTo().window(handle);
                    if (currentUrl().contains(platform)) {
                        break;
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("Switching tabs failed");
        }
    }

Call this method and pass parameter a substring of url of the tab you want to switch to