When you automate a form in Selenium, typing into a field is usually the easy part. Problems start when the test depends on where the cursor is, which element has focus, or whether a modifier key stays pressed during the next action.
You may need to submit a form with Enter, move through controls with Tab, select text with Ctrl+A, or test shortcuts built into the application. Each case needs a slightly different approach. sendKeys() works well for direct input, while the Actions class gives you more control over key sequences and modifiers.
The method you choose depends on the interaction you need to reproduce. Element-level input, held keys, chained shortcuts, and operating-system events are not handled in the same way. The sections below break down each option and where it fits.
What are Keyboard Actions in Selenium?
Keyboard actions in Selenium mean simulating the pressing and releasing of keys on the keyboard.
These actions are important for testing interactive elements like input fields, forms, or shortcuts. Selenium provides various ways to perform keyboard actions, such as typing text, pressing keys, and managing key modifiers like Shift, Ctrl, and Alt.
By automating keyboard actions, testers can analyze real-time user behavior, confirming that the application responds accurately to user inputs during test execution.
Read More: How to handle Action class in Selenium
Common Use Cases for Keyboard Actions
Keyboard actions are useful when the application behaves differently based on the key a user presses. A search field may submit on Enter. A dropdown may only respond to Arrow keys. A form may move focus in the wrong order when the user presses Tab.
You may also need them while testing:
- Text entry in fields that validate input as the user types
- Shortcuts such as Ctrl+A, Ctrl+C, or Shift+Enter
- Backspace and Delete behaviour in editable fields
- Keyboard navigation in menus, autocomplete lists, and modal windows
- Focus movement between inputs, links, buttons, and custom controls
- Key combinations that depend on Ctrl, Shift, Alt, or Command staying pressed
Pro-Tip: After performing a keyboard action in Selenium, verify the resulting application state. For example, after pressing Tab, check which element received focus. After pressing Enter, confirm that the expected form submission or action occurred.
Different ways to handle Keyboard Actions in Selenium
Selenium provides more than one way to send keyboard input because not every interaction works at the same level. Typing into a field is different from holding Ctrl while pressing another key. A browser-level interaction is also different from an operating-system shortcut.
The method you choose should match the way the user interacts with the page.
1. Using sendKeys() on a WebElement
sendKeys() is the most direct option when the keyboard input belongs to a specific element. It is commonly used for text fields, search boxes, text areas, and other editable controls.
WebElement inputField = driver.findElement(By.id("username"));
inputField.sendKeys("testuser");In this example, Selenium sends the text to the element stored in inputField. The element must be visible, enabled, and ready to receive input.
You can also input text in Selenium using SendKeys for individual keys such as Enter, Tab, Backspace, and Escape.
WebElement searchBox = driver.findElement(By.id("search"));
searchBox.sendKeys("Selenium keyboard actions");
searchBox.sendKeys(Keys.ENTER);This approach works well when the test needs to enter text or press a key inside one known element. It is less suitable when the interaction depends on holding a modifier key, moving focus across several elements, or combining keyboard and mouse input.
Also Read: SendKeys in Selenium WebDriver
2. Using Actions.sendKeys()
The Actions class can send keyboard input without calling sendKeys() on a specific WebElement.
Actions actions = new Actions(driver);
actions.sendKeys("Selenium").perform();The input is sent to the element that currently has focus. This matters because the result depends on the active element at the time the action runs.
For example, you can click a field first and then send text through the Actions class.
WebElement inputField = driver.findElement(By.id("message"));
Actions actions = new Actions(driver);
actions
.click(inputField)
.sendKeys("Test message")
.perform();This method is useful when focus is part of the interaction or when the keyboard step belongs to a longer action sequence.
3. Using keyDown() and keyUp() for Modifier Keys
Modifier keys such as Ctrl, Shift, Alt, and Command usually need to remain pressed while another key is sent. The keyDown() and keyUp() methods give you control over that sequence.
The following example selects all text with Ctrl+A.
WebElement inputField = driver.findElement(By.id("message"));
Actions actions = new Actions(driver);
actions
.click(inputField)
.keyDown(Keys.CONTROL)
.sendKeys("a")
.keyUp(Keys.CONTROL)
.perform();keyDown() presses and holds the Ctrl key. The next sendKeys() call sends the letter A while Ctrl is still active. keyUp() then releases the modifier.
Releasing the key is important. If a modifier remains pressed in the action sequence, later input may not behave as expected.
The correct modifier can also depend on the operating system. Ctrl is commonly used on Windows and Linux, while many shortcuts use Command on macOS.
String os = System.getProperty("os.name").toLowerCase();
Keys modifier = os.contains("mac")
? Keys.COMMAND
: Keys.CONTROL;You can then use the selected modifier in the action sequence.
actions
.click(inputField)
.keyDown(modifier)
.sendKeys("a")
.keyUp(modifier)
.perform();This makes the shortcut more suitable for tests that run across different operating systems.
4. Using Keys.chord() for Short Key Combinations
Keys.chord() creates a key combination that can be passed to sendKeys().
WebElement inputField = driver.findElement(By.id("message"));
inputField.sendKeys(Keys.chord(Keys.CONTROL, "a"));This is a compact way to send a simple shortcut such as Ctrl+A, Ctrl+C, or Ctrl+V.
Use Keys.chord() when the combination is short and does not need several steps. Use keyDown() and keyUp() when you need more control over when the modifier is pressed and released.
For example, a sequence that selects text, copies it, moves to another field, and pastes it is easier to read and manage with the Actions class.
Read More: How to handle Alerts and Popups in Selenium?
5. Using perform() to Run the Action Sequence
Methods such as click(), keyDown(), sendKeys(), and keyUp() build an action sequence. Selenium does not run that sequence until perform() is called.
Actions actions = new Actions(driver);
actions
.keyDown(Keys.SHIFT)
.sendKeys("hello")
.keyUp(Keys.SHIFT)
.perform();The sequence above sends the text while Shift is pressed. Depending on the active element and keyboard layout, the resulting text may appear in uppercase.
perform() is not a keyboard event. It is the method that sends the completed sequence to the browser for execution.
If perform() is missing, the actions you added to the sequence will not run.
6. Using the Robot Class
The Java Robot class sends keyboard input at the operating-system level. It does not interact with the page through Selenium or the browser DOM.
Robot robot = new Robot(); robot.keyPress(KeyEvent.VK_CONTROL); robot.keyPress(KeyEvent.VK_C); robot.keyRelease(KeyEvent.VK_C); robot.keyRelease(KeyEvent.VK_CONTROL);
This example sends Ctrl+C to the currently active application window.
Robot may be useful when the interaction happens outside the browser DOM. One example is a native operating-system dialog that Selenium cannot inspect directly.
However, Robot depends on the correct window having focus. It also requires an active desktop session. These requirements make it unreliable for headless execution, parallel runs, and remote test environments.
Use Robot only when the interaction cannot be handled through Selenium’s browser-level APIs.
7. Using JavascriptExecutor
JavaScript can change the value of an element directly.
WebElement inputField = driver.findElement(By.id("username"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(
"arguments[0].value = 'testuser';",
inputField
);This code updates the DOM value, but it does not simulate a user typing on the keyboard.
A real keyboard interaction may trigger events such as keydown, beforeinput, input, and keyup. Directly assigning a value through JavaScript can bypass those events. It may also bypass validation or state updates handled by the application framework.
For that reason, JavascriptExecutor should not be treated as a replacement for sendKeys() or the Actions class. Use it only when the test specifically needs direct DOM manipulation.
Choosing the Right Method
Choose the method for handling keyboard actions in Selenium based on the target element, the key sequence, and the level of control the test needs. The table below compares the six available options.
| Method | Best used for | Key limitation |
|---|---|---|
| WebElement.sendKeys() | Typing text or sending a key to a known element | Less suitable for longer sequences or held modifier keys |
| Actions.sendKeys() | Sending input to the active element or as part of a longer interaction | Depends on the correct element having focus |
| keyDown() and keyUp() | Shortcuts that require Ctrl, Shift, Alt, or Command to remain pressed | The modifier must be released correctly |
| Keys.chord() | Simple combinations such as Ctrl+A or Ctrl+C | Offers less control over multi-step sequences |
| Robot | Native desktop dialogs or input outside the browser DOM | Depends on window focus and an active desktop session |
| JavascriptExecutor | Directly changing an element value in the DOM | Does not reproduce real keyboard input or all related events |
Note: perform() is not listed as a separate method because it only executes the sequence built with the Actions class.
Simulating Keyboard Actions with Examples
The examples below show how common keyboard actions work in a Selenium test. Each example includes the action and the result the test should check afterward.
1. Entering Text in an Input Field
Use sendKeys() when the text belongs to a specific field.
WebElement username = driver.findElement(By.id("username"));
username.sendKeys("testuser");
assertEquals(username.getAttribute("value"), "testuser");The assertion checks the value stored in the field. This is more useful than only confirming that sendKeys() completed without throwing an exception.
Read More: How to Type into a Text Box Using Selenium
2. Submitting a Form with Enter
Some forms allow users to submit from an input field without clicking the submit button.
WebElement searchBox = driver.findElement(By.id("search"));
searchBox.sendKeys("Selenium keyboard actions");
searchBox.sendKeys(Keys.ENTER);
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.urlContains("search"));Pressing Enter does not always submit a form. The behaviour depends on the page implementation and the element that currently has focus. The test should therefore check the result of the submission, such as a URL change, confirmation message, or updated page content.
3. Moving Between Elements with Tab
Tab moves focus to the next focusable element on the page.
WebElement firstName = driver.findElement(By.id("firstName"));
WebElement lastName = driver.findElement(By.id("lastName"));
firstName.click();
firstName.sendKeys(Keys.TAB);
WebElement activeElement = driver.switchTo().activeElement();
assertEquals(activeElement, lastName);The important check is the active element after Tab. Finding lastName and typing into it directly would not confirm that keyboard navigation moved focus correctly.
4. Selecting All Text with Ctrl+A
The Actions class can hold Ctrl while sending another key.
WebElement inputField = driver.findElement(By.id("message"));
inputField.sendKeys("Old message");
Actions actions = new Actions(driver);
actions
.click(inputField)
.keyDown(Keys.CONTROL)
.sendKeys("a")
.keyUp(Keys.CONTROL)
.perform();On macOS, the same shortcut usually uses Keys.COMMAND instead of Keys.CONTROL.
Keys modifier = System.getProperty("os.name")
.toLowerCase()
.contains("mac")
? Keys.COMMAND
: Keys.CONTROL;Use the selected modifier in the action sequence when the test runs across operating systems.
5. Replacing Existing Text
A single Backspace removes one character. To clear the full value with keyboard input, select the existing text first and then press Delete or Backspace.
WebElement inputField = driver.findElement(By.id("message"));
inputField.sendKeys("Old text");
Actions actions = new Actions(driver);
actions
.click(inputField)
.keyDown(modifier)
.sendKeys("a")
.keyUp(modifier)
.sendKeys(Keys.BACK_SPACE)
.sendKeys("New text")
.perform();
assertEquals(inputField.getAttribute("value"), "New text");This reproduces the way a user would replace the entire field value through the keyboard.
6. Typing Uppercase Text with Shift
keyDown() and keyUp() can keep Shift active while Selenium sends text.
WebElement inputField = driver.findElement(By.id("message"));
Actions actions = new Actions(driver);
actions
.click(inputField)
.keyDown(Keys.SHIFT)
.sendKeys("selenium")
.keyUp(Keys.SHIFT)
.perform();
assertEquals(inputField.getAttribute("value"), "SELENIUM");The result can depend on the keyboard layout and the characters being entered. Use this approach when the application needs to process the Shift key itself, not only when the test needs uppercase text.
7. Navigating a Dropdown with Arrow Keys
Custom dropdowns often support Arrow keys and Enter.
WebElement dropdown = driver.findElement(By.id("country"));
dropdown.click();
dropdown.sendKeys(Keys.ARROW_DOWN);
dropdown.sendKeys(Keys.ARROW_DOWN);
dropdown.sendKeys(Keys.ENTER);
assertEquals(dropdown.getAttribute("value"), "Canada");The exact assertion depends on how the component stores its selected value. A native <select> element may expose the value directly, while a custom component may update text, an ARIA attribute, or a hidden input.
8. Closing a Modal with Escape
Escape is commonly used to close modal windows, menus, and overlays.
WebElement modal = driver.findElement(By.id("settingsModal"));
Actions actions = new Actions(driver);
actions.sendKeys(Keys.ESCAPE).perform();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.invisibilityOf(modal));This example sends Escape to the currently focused element and waits until the modal is no longer visible. The check confirms the application response rather than only confirming that the key was sent.
Conclusion
Keyboard actions in Selenium are not limited to entering text. They also cover focus movement, form submission, shortcuts, text selection, dropdown navigation, and other interactions that depend on specific keys or key combinations.
Use sendKeys() for direct input to a known element. Use the Actions class when the test needs held modifiers, focus-based input, or a longer sequence. Keep Robot for native desktop cases, and do not treat JavaScript value assignment as real keyboard input. After every action, verify the result in the application rather than assuming the key press worked as expected.