1

I need to perform a key press combination on Selenium Chrome driver. The action is not sending test to text box or clicking on a button.

I am actually not interested in sending keys to any specific web element. For example, I would like to perform command+R (reload on Mac OS). (Reloading is just an example for the explanation, not my ultimate goal)

My code is the following:

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

I have spend hours searching and trying only got no luck.

Any help is appreciated!

1 Answer 1

2

The WebDriver spec is element-focussed, and doesn't define any method to send keys to the window, the screen, to browser chrome - only to elements.

Use of the Selenium Actions class for Cmd-R works on my Mac in Firefox (45), but only when run in the foreground - and seemingly not at all in Chrome. Presumably this is down to differences in the implementations of the remote Keyboard implementation, which it's probably best not to rely upon.


The most efficient way and non-platform-specific way to request a page reload is using JavaScript:

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

However, JavaScript doesn't let you "just send keys".


The only other way is via the Java AWT Robot class:

Robot robot = new java.awt.Robot();
robot.keyPress(KeyEvent.VK_META);  // See: http://stackoverflow.com/a/15419192/954442
robot.keyPress(KeyEvent.VK_R);
robot.keyRelease(KeyEvent.VK_R);
robot.keyRelease(KeyEvent.VK_META);

This "blindly" sends key combinations to whichever windows / components are on screen at the time, so if your browser window has been hidden or minimised, this will not work.

4
  • Thanks for the help. 1.In order to let the robot way to work, my current focus window has to be the Chrome driver window. 2. My point is not refreshing the page, it's performing a key combination (still good to know). 3. Is there a Selenium way to do the above operation?
    – conan_z
    Apr 9, 2016 at 22:13
  • Yes. Perhaps I should clarify this is another reason to prefer the JavaScript approach, assuming you really just want to reload the page, and the Cmd-R is just an example. Apr 9, 2016 at 22:16
  • Is there a Selenium way to achieve it?
    – conan_z
    Apr 9, 2016 at 22:24
  • Thank you for pointing out Actions does not work in Chrome Driver. I wish I asked this question several hours earlier.
    – conan_z
    Apr 10, 2016 at 17:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.