简体   繁体   中英

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. Additionally, WebDriver in general doesn't support automating "manually" opened tabs, like those opened with Control+t . Specific drivers may support that functionality, but it's not a globally supported part of the API contract.

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. 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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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