I encountered an issue where selenium is unable to press and hold a key that is not included in the list of predefined keys:
Keys.SHIFT,
Keys.CONTROL,
Keys.ALT,
Keys.META,
Keys.COMMAND,
Keys.LEFT_ALT,
Keys.LEFT_CONTROL,
Keys.LEFT_SHIFT
In my application, instructions are displayed only when the space key is pressed and held down. I need to create browser tests for this scenario.
I am using ProtractorJS, but it seems like there is a general limitation in selenium for performing such actions. Whenever I try to use keyDown for a non-modifier key, an exception is thrown with a message stating: "Key Down / Up events only make sense for modifier keys."
Here is the link to the Selenium Java code: https://github.com/SeleniumHQ/selenium/blob/master/java/client/src/org/openqa/selenium/interactions/internal/SingleKeyAction.java#L48
The same check can be found in Selenium JS code: https://github.com/SeleniumHQ/selenium/blob/master/javascript/webdriver/actionsequence.js#L301
Is there a way to press and hold a non-modifier key? Specifically, the space key in my case.
UPDATE: Thanks to the answer provided by Florent B., I was able to make it work after some modifications. I had to switch to a frame and dispatch the event to the document instead of a specific element for my use case.
browser.switchTo().frame('workspace');
const SIMULATE_KEY =
"var e = new Event('keydown');" +
"e.keyCode = 32;" + //spacebar keycode
"e.which = e.keyCode;" +
"e.altKey = false;" +
"e.ctrlKey = false;" +
"e.shiftKey = false;" +
"e.metaKey = false;" +
"e.bubbles = true;" +
"document.dispatchEvent(e);";
browser.executeScript(SIMULATE_KEY);