Selenium Chrome 驱动程序将按键组合发送到 window

Selenium Chrome Driver send key press combinations to window

我需要在 Selenium Chrome 驱动程序上执行组合键。 该操作不是将测试发送到文本框或单击按钮。

我实际上对向任何特定 Web 元素发送密钥不感兴趣。 例如,我想执行 command+R (reload on Mac OS)。 (重装只是举例说明,并非我的最终目的)

我的代码如下:

public static void keyPressCombnaiton() {
    Actions action = new Actions(browser);
    action.keyDown(Keys.COMMAND)
          .sendKeys("r")
          .keyUp(Keys.COMMAND)
          .build()
          .perform();
}

我花了几个小时搜索和尝试,但没有成功。

感谢任何帮助!

WebDriver spec is element-focussed,并且没有定义任何方法来将键发送到 window、屏幕、浏览器 chrome - 仅发送到元素。

将 Selenium Actions class 用于 Cmd-R 在我的 Mac 在 Firefox (45) 中,但仅当 运行 在前台时 - 而在 Chrome 中似乎根本没有。大概这是由于远程键盘实现的实现不同,最好不要依赖它。


请求页面重新加载的最有效方式和非平台特定方式是使用Java脚本:

((JavascriptExecutor) driver).executeScript("document.location.reload(true)");

但是,Java脚本不允许您"just send keys"。


唯一的其他方法是通过 Java AWT 机器人 class:

Robot robot = new java.awt.Robot();
robot.keyPress(KeyEvent.VK_META);  // See: 
robot.keyPress(KeyEvent.VK_R);
robot.keyRelease(KeyEvent.VK_R);
robot.keyRelease(KeyEvent.VK_META);

此 "blindly" 将组合键发送到当时屏幕上的任何 windows / 组件,因此如果您的浏览器 window 已被隐藏或最小化,这将不起作用。