Switch tabs using Selenium WebDriver with Java Switch tabs using Selenium WebDriver with Java selenium selenium

Switch tabs using Selenium WebDriver with Java


    psdbComponent.clickDocumentLink();    ArrayList<String> tabs2 = new ArrayList<String> (driver.getWindowHandles());    driver.switchTo().window(tabs2.get(1));    driver.close();    driver.switchTo().window(tabs2.get(0));

This code perfectly worked for me. Try it out. You always need to switch your driver to new tab, before you want to do something on new tab.


This is a simple solution for opening a new tab, changing focus to it, closing the tab and return focus to the old/original tab:

@Testpublic void testTabs() {    driver.get("https://business.twitter.com/start-advertising");    assertStartAdvertising();    // considering that there is only one tab opened in that point.    String oldTab = driver.getWindowHandle();    driver.findElement(By.linkText("Twitter Advertising Blog")).click();    ArrayList<String> newTab = new ArrayList<String>(driver.getWindowHandles());    newTab.remove(oldTab);    // change focus to new tab    driver.switchTo().window(newTab.get(0));    assertAdvertisingBlog();    // Do what you want here, you are in the new tab    driver.close();    // change focus back to old tab    driver.switchTo().window(oldTab);    assertStartAdvertising();    // Do what you want here, you are in the old tab}private void assertStartAdvertising() {    assertEquals("Start Advertising | Twitter for Business", driver.getTitle());}private void assertAdvertisingBlog() {    assertEquals("Twitter Advertising", driver.getTitle());}


There is a difference how web driver handles different windows and how it handles different tabs.

Case 1:
In case there are multiple windows, then the following code can help:

//Get the current window handleString windowHandle = driver.getWindowHandle();//Get the list of window handlesArrayList tabs = new ArrayList (driver.getWindowHandles());System.out.println(tabs.size());//Use the list of window handles to switch between windowsdriver.switchTo().window(tabs.get(0));//Switch back to original windowdriver.switchTo().window(mainWindowHandle);


Case 2:
In case there are multiple tabs in the same window, then there is only one window handle. Hence switching between window handles keeps the control in the same tab.
In this case using Ctrl + \t (Ctrl + Tab) to switch between tabs is more useful.

//Open a new tab using Ctrl + tdriver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");//Switch between tabs using Ctrl + \tdriver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");

Detailed sample code can be found here:
http://design-interviews.blogspot.com/2014/11/switching-between-tabs-in-same-browser-window.html