简体   繁体   中英

Selenium 3: Switching between the tabs

The code that worked with Selenium 2 stopped working with Selenium 3.

This code does not work any more neither in Chrome nor in Firefox.

driver.get("http://the-internet.herokuapp.com/windows");
String firstWindow = driver.getWindowHandle();
driver.findElement(By.linkText("Click Here")).click();
driver.switchTo().window(firstWindow);

I found that for Firefox there is a workaround:

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL, Keys.PAGE_DOWN);

However, nothing works for Chrome.
Please help

I think you are indeed suffering from a new bug (or maybe intended behaviour?).

After checking out your code and testing it, I noticed that even though a new tab gets opened and focused in Chrome the driver does not automatically switch to that tab.

You have to add .switchTo().window(secondWindow) so your driver switches to the new (and active) tab.

So .switchTo() doesn't focus the tab, which the driver is using and thus it looks like you just stay in the second tab, even though the driver itself switched back to the first window.

Here is some code that might help you understand the issue:

    driver.get("http://the-internet.herokuapp.com/windows");
    String firstWindow = driver.getWindowHandle();
    System.out.print("First windowhandle: " + firstWindow + "\n");

    System.out.print("Clicking on 'Click Here' \n");
    driver.findElement(By.linkText("Click Here")).click();

    Set<String> stringSet = driver.getWindowHandles();
    System.out.print("All windowhandles: " + stringSet + "\n");
    List<String> handles = new ArrayList<>(stringSet);

    System.out.print("Switching to new window \n");
    driver.switchTo().window(handles.get(1));
    //wait for Title to change to second tab title
    new WebDriverWait(driver, 10).until(ExpectedConditions.titleIs("New Window"));

    System.out.print("Second (and current) windowhandle: " + driver.getWindowHandle() + "\n");

    System.out.print("Switching back to first Window. \n");
    driver.switchTo().window(firstWindow);

    //wait for Title to change back to first title
    new WebDriverWait(driver, 10).until(ExpectedConditions.titleIs("The Internet"));

    System.out.print("Last used windowhandle: " + driver.getWindowHandle() + "\n");

If you run this code you will notice two things:
a) the driver will switch to the correct tab (see the WindowHandle output)
b) the currently used tab the driver uses will not be properly focused in Chrome

This does seem to be a bug.

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