Monday, November 24, 2014

Switching between tabs in same browser window using Selenium WebDriver

Recently I was supposed to automate a test-case which needed me to perform the following steps:

1. Open a browser window
2. Navigate to a URL
3. Perform some operations
4. Open a new tab in the "same" browser window
5. Perform some operations in the newly opened tab
6. Switch back to the previously opened tab
7. Perform some operations in this tab

Most of the resources I have come across while I was dealing with this particular problem talked about opening a new browser window (not a new tab in the same window), using windowHandles to switch between the windows.

The typical catch in this problem is:
When you open a new browser window, you get two window handles. Then they can be used to switch between them.
But when you open a new tab, there is a single window handle. So switching between tabs is not achieved by calling driver.switchTo().window(<windowHandle>)

So I used the following work-around:
1. Open a new tab using Ctrl + t
2. Driver control automatically switches to the newly opened tab
3. Perform the required operations here.
4. Next switch back to the old tab using Ctrl + Tab. You need to keep pressing this unless you reach the desired tab.
5. Once the desired tab is reached, then perform the operations in that tab.

Sample Code:
Get the current window handle and open a new tab using Ctrl + t
        driver.get("http://google.com");
        String windowHandle = driver.getWindowHandle();
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");

The size of the output of getWindowHandles() is 1 which means that there is one single window handle
        ArrayList tabs = new ArrayList (driver.getWindowHandles());
        System.out.println(tabs.size());
        driver.switchTo().window(tabs.get(0)); 

The control is now in the new tab
        driver.get("http://bing.com");
        //perform other operations.

Switch to the old tab using Ctrl + Tab
        driver.switchTo().window(mainWindowHandle);
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");
        driver.switchTo().defaultContent();

3 comments: