Using Selenium WebDriver with JAVA. I am trying to automate a functionality where I have to open a new tab do some operations there and come back to previous tab (Parent). I
Work around
Assumption : By Clicking something on your web page leads to open a new tab.
Use below logic to switch to second tab.
new Actions(driver).sendKeys(driver.findElement(By.tagName("html")), Keys.CONTROL).sendKeys(driver.findElement(By.tagName("html")),Keys.NUMPAD2).build().perform();
In the same manner you can switch back to first tab again.
new Actions(driver).sendKeys(driver.findElement(By.tagName("html")), Keys.CONTROL).sendKeys(driver.findElement(By.tagName("html")),Keys.NUMPAD1).build().perform();
The flaw with the selected answer is that it unnecessarily assumes order in webDriver.getWindowHandles()
. The getWindowHandles()
method returns a Set
, which does not guarantee order.
I used the following code to change tabs, which does not assume any ordering.
String currentTabHandle = driver.getWindowHandle();
String newTabHandle = driver.getWindowHandles()
.stream()
.filter(handle -> !handle.equals(currentTabHandle ))
.findFirst()
.get();
driver.switchTo().window(newTabHandle);
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL,Keys.SHIFT,Keys.TAB);
This method helps in switching between multiple windows. The restricting problem with this method is that it can only be used so many times until the required window is reached. Hope it helps.