We use cookies to analyze site traffic and show personalized ads. You can accept all cookies or decline personalized advertising.
Learn more in our Privacy Policy.
Simulating advanced typing, selection, and keyboard shortcuts using Actions and Keys in Java
In this practice lab, you will learn how to simulate real keyboard behavior in Selenium using the Actions class and the Keys enum.
Instead of only using element.sendKeys("text"), you will:
Actions is used to build complex user interactions step by step (keyboard, mouse, or combined).
keyDown(), sendKeys(), keyUp(), etc..perform() at the endWhen to use it
element.sendKeys() is not enoughKeys provides special keys: SHIFT, CONTROL, COMMAND, ENTER, TAB, ARROW_LEFT, ARROW_UP, etc.
Instead of magic strings, you use Keys.SOMETHING for clarity and stability.
When to use it
Designated element:
actions.sendKeys(textField, "Selenium!")Active element:
actions.sendKeys("abc")In this practice, imagine a simple page called "Keyboard Playground".
Interact with the form directly to see how Selenium would locate these elements!
Selenium!X to cut the selection.V twice to paste the same text two times.SeleniumSelenium!Your Selenium script will perform these exact keyboard steps using Actions and Keys.
12345678910111213141516WebElement textField = driver.findElement(By.id("textInput"));
Keys cmdCtrl = Platform.getCurrent().is(Platform.MAC) ? Keys.COMMAND : Keys.CONTROL;
new Actions(driver)
.sendKeys(textField, "Selenium!")
.sendKeys(Keys.ARROW_LEFT)
.keyDown(Keys.SHIFT)
.sendKeys(Keys.ARROW_UP)
.keyUp(Keys.SHIFT)
.keyDown(cmdCtrl)
.sendKeys("xvv")
.keyUp(cmdCtrl)
.perform();
driver.quit();id="textInput".COMMAND on Mac, CONTROL on other operating systems.driver.textField and types the text "Selenium!" into it."xvv" while Ctrl/Cmd is held:x → Cut the selected textv → Paste oncev → Paste again, resulting in SeleniumSelenium!Prefer explicit element targeting (sendKeys(textField, "...")) over relying on the active element. It makes your tests more stable and easier to debug.
Keep keyboard action chains small and readable. If a chain becomes too long, split it into logical steps for better maintainability and debugging.
Always use the Keys enum (e.g. Keys.SHIFT, Keys.ARROW_LEFT) instead of magic values; this makes shortcuts and cursor movements self-explanatory for anyone reading your test.