问题
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);
回答1:
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.
回答2:
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:
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);
来源:https://stackoverflow.com/questions/31162378/how-to-press-altt-in-selenium-webdriver-with-java-i-want-to-switch-tabs-by-p