Java – use webdriver to click the link in the newly opened tab

Someone can help me in this situation:

The scenario is: there is a web page, and I only open all specified links in the new tab Now I try to click any link in the newly opened tab Try the following, but it just clicks a link in the main / first tab, not in the new tab

new Actions(driver).sendKeys(Keys.CONTROL).sendKeys(Keys.NUMPAD1).perform();
driver.findElement(By.tagName("body")).sendKeys(Keys.CONTROL,Keys.TAB);
List<WebElement> links=driver.findElements(By.xpath("//a[contains(@href,'http')]"));
links.get(0).click();

Solution

You need to use switchTo(windowHandle); Command to access the second tab

Before opening the second tab – get the windowhandle of the open tab:

String mainWindow = driver.getWindowHandle();

Then perform the operation of opening the second tab Now you need to know the handle to the second tab and switch control to it:

Set<String> handles = driver.getWindowHandles();  
for (String handle : handles) {
    if (!handle.equals(mainWindow)) {
          driver.switchTo().window(handle);
          break;
    }
}

Your action on the second tab will now take place in the second window When you are finished and need to interact with the first tag again: driver switchTo(). defaultContent();

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>