简体   繁体   English

无法使用Selenium Webdriver在Internet Explorer中将焦点切换到newtab /窗口

[英]Unable to switch focus to newtab/window in Internet Explorer using Selenium Webdriver

The problem here is, I'm unable to focus to the new tab/window both, instead the focus remains in the first one. 这里的问题是,我无法同时将焦点集中在新的标签页/窗口上,而是将焦点始终放在第一个标签页/窗口上。 Please help. 请帮忙。

driver=new InternetExplorerDriver();
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
//driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"n");
for (String winHandle : driver.getWindowHandles()) 
{
    driver.switchTo().window(winHandle);
}
driver.get("https://google.com/");

The IE driver doesn't support enumeration of tabs within a window. IE驱动程序不支持窗口中选项卡的枚举。 Additionally, WebDriver in general doesn't support automating "manually" opened tabs, like those opened with Control+t . 此外,WebDriver通常不支持自动化“手动”打开的选项卡,例如使用Control+t打开的选项卡。 Specific drivers may support that functionality, but it's not a globally supported part of the API contract. 特定的驱动程序可能支持该功能,但这不是API合同的全球支持部分。

The vast majority of times users are attempting to "manually open a new tab, switch to it, and automate it," the use case isn't entirely thought through. 用户尝试“手动打开一个新标签页,切换到该标签页并使其自动化”的绝大多数情况下,用例并未得到充分考虑。 Since you decline to state why you want to perform this action, as opposed to starting a new driver instance in a new window, it's impossible to speculate what course of action you ought to be taking. 由于您拒绝说明为什么要执行此操作(而不是在新窗口中启动新的驱动程序实例),因此无法推测您应该采取什么措施。

The simplest way of achieving what you're asking for is something along these lines: 满足您要求的最简单方法是遵循以下原则:

  1. Get a handle on the initial window. 在初始窗口上获取一个句柄。
  2. Open the new window. 打开新窗口。
  3. Get a list of handles for all the open windows at this point, and remove the initial window handle. 此时,获取所有打开的窗口的句柄列表,然后删除初始窗口句柄。
  4. Switch to the remaining window handle in the list retrieved in the previous step. 切换到上一步获取的列表中的其余窗口句柄。

Try this , after you have opened the tab use Java robot to switch it. 打开标签页后,尝试使用此方法 ,使用Java机械手对其进行切换。 The following code use the same principle that solves your problem. 以下代码使用解决您问题的相同原理。

ArrayList<String> tabs2 = new ArrayList<String>(driver.getWindowHandles());
    System.out.println(tabs2.size());

    for (int i = tabs2.size()-1; i>=0; i--) {
        Thread.sleep(2000);
        driver.switchTo().window(tabs2.get(i));
        Robot robot = new Robot();

        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_TAB);
        robot.keyRelease(KeyEvent.VK_TAB);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        System.out.println(driver.getTitle() + "i: " + i);
        driver.close();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM