4

I currently have a Java application using Selenium Webdriver and google chrome. There is a lot of cases in which the user will be switching back and forth between tabs. I'm trying to get the program to identify the selected tab by the user, and switch the drivers focus to that tab. Currently the code only runs on whatever tab is focused on, regardless of what the user switches it to. I understand to switch the focus I can use

driver.switchTo().window(currentTab);

However, I can't seem to figure out what the current tab index is. I would like to avoid using the "tabs" extension from google chrome. I've found a few online posts about this subject but none have seem to have a solution. Any help would be appreciated.

Mustahsan
  • 3,852
  • 1
  • 18
  • 34
M. Rogers
  • 367
  • 4
  • 18

1 Answers1

1

You can get current tab by getWindowHandle() and then get its index of current tab from list you get from getWindowHandles(). Try this code:

String currentTab = driver.getWindowHandle();
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
int index = tabs.indexOf(currentTab);

NOTE Window handle is a Unique Identifer of webpage in browser tab

Mustahsan
  • 3,852
  • 1
  • 18
  • 34
  • So this gets the handle of the tab selected directly by the driver, it will not get the handle when selected by the user. I'm trying to get the handle when the tab is changed directly in the browser. – M. Rogers Sep 09 '19 at 14:08