How to press “ALT+T” in Selenium webdriver with ja

2019-07-20 22:15发布

I have used below code, but it throws an error saying "Cannot focus on element". Please help.

String selectAll = Keys.chord(Keys.ALT,"T");
driver.findElement(By.tagName("html")).sendKeys(selectAll);

3条回答
淡お忘
2楼-- · 2019-07-20 22:44

You can send ShortcutKeys like Alt + Tab to driver without using element by using Actions.

public static void sendShortCut(WebDriver driver) {
    Actions action = new Actions(driver);
     action.sendKeys(Keys.chord(Keys.CONTROL, "T")).build().perform();
}

However your goal was to switch to the window/tab.In Selenium both window and tab are same.

I've provided you two solutions which is self explanatory from the name of the functions

public static void switchToWindowByTitle(WebDriver driver, String title) {
    Set<String> Handles = driver.getWindowHandles();
    for (String handle : Handles) {
        driver.switchTo().window(handle);
        String drivertitle = driver.getTitle().trim();
        if (drivertitle.equals(title)) {
            break;
        }
    }
}

//Index is 0 based
public static void switchToWindowByIndex(WebDriver driver, int index) {
    Set<String> handles = driver.getWindowHandles();
    if (handles.size() > index) {
        String handle = handles.toArray()[index].toString();
        driver.switchTo().window(handle);
    }
}
查看更多
等我变得足够好
3楼-- · 2019-07-20 22:59

You can open another tab using:

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");

and switch to tabs by using:

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL, Keys.PAGE_DOWN);
查看更多
The star\"
4楼-- · 2019-07-20 23:10

The best way to switch tabs would be to use switchTo(), if you know the new window name:

driver.switchTo().window(WINDOW_NAME);

Otherwise get a list of the open windows and switch using that:

List<String> openTabs = driver.getWindowHandles();

    for(String tab in openTabs) {
     driver.switchTo().window(openTabs.get(tab);
    }

So you can iterate over the open windows until you find the one you need.

查看更多
登录 后发表回答