Keyboard Actions in Selenium WebDriver
Keyboard Actions in Selenium WebDriver are advanced keyboard interactions used to automate actions such as typing, pressing individual keys, using keyboard shortcuts, selecting text, copying and pasting content, navigating between elements, submitting forms, and interacting with applications that depend on keyboard events.
In Selenium Java, keyboard interactions are commonly performed using the Actions class together with Keys from org.openqa.selenium.Keys. Keyboard actions can be combined with mouse actions to create realistic and reusable browser automation workflows.
Selenium Training Course | Register for Course Demo
1. What are Keyboard Actions?
Keyboard Actions are automated keyboard operations performed against web elements or the active browser context. Selenium can simulate key presses such as Enter, Tab, Shift, Control, Alt, Escape, Arrow keys, Function keys, and many other keyboard inputs.
Actions actions = new Actions(driver);
actions.sendKeys(Keys.ENTER).perform();
2. Why are Keyboard Actions Important?
Modern web applications often depend on keyboard events for navigation, shortcuts, form submission, accessibility, menus, search boxes, and rich user interfaces.
- Automates keyboard-based workflows.
- Supports keyboard shortcuts.
- Supports form navigation.
- Can simulate Enter, Tab, Escape and Arrow keys.
- Supports text selection.
- Supports copy and paste operations.
- Can be combined with mouse actions.
- Helps test keyboard accessibility.
- Supports complex web application interactions.
3. Actions Class
The Actions class provides methods for advanced mouse and keyboard interactions. It can create sequences involving keyboard keys, mouse movements, clicks, holds, releases, and other interactions.
Actions actions = new Actions(driver);
4. Keys Class
The Keys class contains constants representing keyboard keys that can be used with Selenium keyboard interactions.
import org.openqa.selenium.Keys;
Examples include Keys.ENTER, Keys.TAB, Keys.ESCAPE, Keys.SHIFT, Keys.CONTROL, Keys.ALT, and arrow keys.
5. Required Imports
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.Keys;
6. Basic Keyboard Action Syntax
Actions actions = new Actions(driver);
actions.sendKeys(Keys.ENTER).perform();
The general workflow is:
Locate Element
↓
Create Actions Object
↓
Choose Keyboard Key
↓
Build Keyboard Action
↓
Perform Action
↓
Validate Result
7. Sending Text Using sendKeys()
The sendKeys() method can be used to send text or keyboard keys to the current active element.
new Actions(driver)
.sendKeys("Selenium Automation")
.perform();
8. Sending Keys to a WebElement
WebElement searchBox = driver.findElement(
By.id("search")
);
new Actions(driver)
.click(searchBox)
.sendKeys("Selenium")
.perform();
9. Using WebElement.sendKeys()
For simple text input, WebElement.sendKeys() is often sufficient. The Actions API becomes particularly useful for advanced keyboard sequences and combinations.
WebElement username = driver.findElement(
By.id("username")
);
username.sendKeys("testuser");
10. Actions sendKeys() vs WebElement sendKeys()
| Feature | WebElement.sendKeys() | Actions.sendKeys() |
| Simple text input | Yes | Yes |
| Keyboard shortcuts | Limited | Yes |
| Active element interaction | Element-specific | Yes |
| Key combinations | Possible for element input | Better suited |
| Advanced sequences | Limited | Yes |
11. Pressing Enter Key
The Enter key is commonly used to submit forms, perform searches, confirm selections, or activate controls.
WebElement searchBox = driver.findElement(
By.id("search")
);
new Actions(driver)
.click(searchBox)
.sendKeys("Selenium")
.sendKeys(Keys.ENTER)
.perform();
12. Pressing Tab Key
The Tab key moves focus to the next focusable element.
new Actions(driver)
.sendKeys(Keys.TAB)
.perform();
13. Pressing Shift + Tab
Shift + Tab usually moves focus to the previous focusable element.
new Actions(driver)
.keyDown(Keys.SHIFT)
.sendKeys(Keys.TAB)
.keyUp(Keys.SHIFT)
.perform();
14. Pressing Escape Key
The Escape key is frequently used to close menus, dialogs, popups, dropdowns, and modal interfaces.
new Actions(driver)
.sendKeys(Keys.ESCAPE)
.perform();
15. Pressing Space Key
The Space key can be used to activate focused controls such as checkboxes, buttons, or custom interactive elements.
new Actions(driver)
.sendKeys(Keys.SPACE)
.perform();
16. Pressing Arrow Keys
Arrow keys are useful for dropdowns, menus, sliders, calendars, custom controls, and keyboard navigation.
new Actions(driver)
.sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ENTER)
.perform();
17. Right Arrow Key
new Actions(driver)
.sendKeys(Keys.ARROW_RIGHT)
.perform();
18. Left Arrow Key
new Actions(driver)
.sendKeys(Keys.ARROW_LEFT)
.perform();
19. Up Arrow Key
new Actions(driver)
.sendKeys(Keys.ARROW_UP)
.perform();
20. Down Arrow Key
new Actions(driver)
.sendKeys(Keys.ARROW_DOWN)
.perform();
21. Using Backspace
The Backspace key can be used to remove characters from an input field when the cursor is positioned appropriately.
new Actions(driver)
.sendKeys(Keys.BACK_SPACE)
.perform();
22. Using Delete Key
new Actions(driver)
.sendKeys(Keys.DELETE)
.perform();
23. Using Home Key
The Home key can move the cursor to the beginning of a line or navigate to the beginning of a list depending on the application.
new Actions(driver)
.sendKeys(Keys.HOME)
.perform();
24. Using End Key
new Actions(driver)
.sendKeys(Keys.END)
.perform();
25. Using Page Up
new Actions(driver)
.sendKeys(Keys.PAGE_UP)
.perform();
26. Using Page Down
new Actions(driver)
.sendKeys(Keys.PAGE_DOWN)
.perform();
27. Using Control Key
The Control key is commonly used for keyboard shortcuts such as Ctrl+A, Ctrl+C, Ctrl+V, and Ctrl+S.
new Actions(driver)
.keyDown(Keys.CONTROL)
.sendKeys("a")
.keyUp(Keys.CONTROL)
.perform();
28. Using Shift Key
The Shift key can be used to create uppercase characters, select text, and execute Shift-based shortcuts.
new Actions(driver)
.keyDown(Keys.SHIFT)
.sendKeys("selenium")
.keyUp(Keys.SHIFT)
.perform();
29. Using Alt Key
new Actions(driver)
.keyDown(Keys.ALT)
.sendKeys("a")
.keyUp(Keys.ALT)
.perform();
30. Using Meta Key
The Meta key can be relevant to platform-specific shortcuts, particularly on macOS.
new Actions(driver)
.keyDown(Keys.META)
.sendKeys("a")
.keyUp(Keys.META)
.perform();
31. Understanding keyDown()
The keyDown() method presses a modifier key and keeps it active until it is released.
new Actions(driver)
.keyDown(Keys.CONTROL)
.sendKeys("a")
.perform();
When a modifier is intentionally held, it should normally be released using keyUp().
32. Understanding keyUp()
The keyUp() method releases a previously pressed modifier key.
new Actions(driver)
.keyDown(Keys.CONTROL)
.sendKeys("a")
.keyUp(Keys.CONTROL)
.perform();
33. Ctrl + A Select All
Ctrl+A is commonly used to select all text inside an input field.
WebElement input = driver.findElement(
By.id("username")
);
new Actions(driver)
.click(input)
.keyDown(Keys.CONTROL)
.sendKeys("a")
.keyUp(Keys.CONTROL)
.perform();
34. Ctrl + C Copy
new Actions(driver)
.keyDown(Keys.CONTROL)
.sendKeys("c")
.keyUp(Keys.CONTROL)
.perform();
35. Ctrl + V Paste
new Actions(driver)
.keyDown(Keys.CONTROL)
.sendKeys("v")
.keyUp(Keys.CONTROL)
.perform();
36. Ctrl + X Cut
new Actions(driver)
.keyDown(Keys.CONTROL)
.sendKeys("x")
.keyUp(Keys.CONTROL)
.perform();
37. Ctrl + Z Undo
new Actions(driver)
.keyDown(Keys.CONTROL)
.sendKeys("z")
.keyUp(Keys.CONTROL)
.perform();
38. Ctrl + Y Redo
new Actions(driver)
.keyDown(Keys.CONTROL)
.sendKeys("y")
.keyUp(Keys.CONTROL)
.perform();
39. Ctrl + S Save Shortcut
Applications with custom save shortcuts can be tested using keyboard combinations.
new Actions(driver)
.keyDown(Keys.CONTROL)
.sendKeys("s")
.keyUp(Keys.CONTROL)
.perform();
40. Ctrl + F Search Shortcut
new Actions(driver)
.keyDown(Keys.CONTROL)
.sendKeys("f")
.keyUp(Keys.CONTROL)
.perform();
41. Ctrl + A and Replace Text
A common automation workflow is selecting existing text and replacing it with new content.
WebElement input = driver.findElement(
By.id("email")
);
new Actions(driver)
.click(input)
.keyDown(Keys.CONTROL)
.sendKeys("a")
.keyUp(Keys.CONTROL)
.sendKeys("[email protected]")
.perform();
42. Selecting Text with Shift
Shift combined with arrow keys can select text in applications that support standard keyboard selection behavior.
new Actions(driver)
.keyDown(Keys.SHIFT)
.sendKeys(Keys.ARROW_RIGHT)
.sendKeys(Keys.ARROW_RIGHT)
.sendKeys(Keys.ARROW_RIGHT)
.keyUp(Keys.SHIFT)
.perform();
43. Keyboard Navigation Between Form Fields
Keyboard navigation can be used to verify that users can move through a form using the Tab key.
new Actions(driver)
.sendKeys("John")
.sendKeys(Keys.TAB)
.sendKeys("[email protected]")
.sendKeys(Keys.TAB)
.sendKeys("1234567890")
.perform();
44. Form Submission Using Enter
WebElement username = driver.findElement(
By.id("username")
);
username.sendKeys("testuser");
new Actions(driver)
.sendKeys(Keys.ENTER)
.perform();
45. Keyboard Action on Search Box
WebElement search = driver.findElement(
By.name("q")
);
new Actions(driver)
.click(search)
.sendKeys("Selenium WebDriver")
.sendKeys(Keys.ENTER)
.perform();
46. Keyboard Actions on Login Form
WebElement username = driver.findElement(
By.id("username")
);
WebElement password = driver.findElement(
By.id("password")
);
new Actions(driver)
.click(username)
.sendKeys("testuser")
.sendKeys(Keys.TAB)
.sendKeys("Password123")
.sendKeys(Keys.ENTER)
.perform();
47. Keyboard Actions with Dropdown
Custom dropdowns can sometimes be navigated using arrow keys and Enter.
WebElement dropdown = driver.findElement(
By.id("country")
);
new Actions(driver)
.click(dropdown)
.sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ENTER)
.perform();
48. Keyboard Actions with Autocomplete
Autocomplete fields often require typing text and selecting a suggestion using the keyboard.
WebElement city = driver.findElement(
By.id("city")
);
new Actions(driver)
.click(city)
.sendKeys("Mumbai")
.pause(Duration.ofMillis(500))
.sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ENTER)
.perform();
49. Keyboard Actions with Modal Dialog
Escape can be used to close a custom modal or dialog when the application supports keyboard dismissal.
new Actions(driver)
.sendKeys(Keys.ESCAPE)
.perform();
50. Keyboard Actions with Menus
Keyboard actions can be used to navigate custom menus using arrow keys and Enter.
new Actions(driver)
.sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ARROW_RIGHT)
.sendKeys(Keys.ENTER)
.perform();
51. Keyboard Actions with Checkboxes
A focused checkbox can often be toggled using the Space key.
WebElement checkbox = driver.findElement(
By.id("terms")
);
new Actions(driver)
.click(checkbox)
.sendKeys(Keys.SPACE)
.perform();
52. Keyboard Actions with Radio Buttons
WebElement radio = driver.findElement(
By.id("male")
);
new Actions(driver)
.click(radio)
.sendKeys(Keys.SPACE)
.perform();
53. Keyboard Actions with Buttons
When a button has keyboard focus, Enter or Space may activate it depending on the control.
WebElement button = driver.findElement(
By.id("submit")
);
new Actions(driver)
.click(button)
.sendKeys(Keys.ENTER)
.perform();
54. Keyboard Actions with Text Areas
WebElement textarea = driver.findElement(
By.id("comments")
);
new Actions(driver)
.click(textarea)
.sendKeys("This is a Selenium keyboard test.")
.perform();
55. Keyboard Actions with Multiline Text
For controls that interpret Enter as a newline, keyboard actions can create multiline input.
new Actions(driver)
.sendKeys("First line")
.sendKeys(Keys.ENTER)
.sendKeys("Second line")
.perform();
56. Keyboard Actions with Contenteditable
Rich text editors often use contenteditable elements and can require Actions-based keyboard input.
WebElement editor = driver.findElement(
By.cssSelector("[contenteditable='true']")
);
new Actions(driver)
.click(editor)
.sendKeys("Selenium keyboard automation")
.perform();
57. Keyboard Actions for Text Selection
WebElement input = driver.findElement(
By.id("message")
);
new Actions(driver)
.click(input)
.keyDown(Keys.CONTROL)
.sendKeys("a")
.keyUp(Keys.CONTROL)
.perform();
58. Keyboard Actions for Clearing Text
A common keyboard approach is selecting all text and pressing Backspace.
new Actions(driver)
.keyDown(Keys.CONTROL)
.sendKeys("a")
.keyUp(Keys.CONTROL)
.sendKeys(Keys.BACK_SPACE)
.perform();
59. clear() vs Keyboard Clearing
| Aspect | clear() | Keyboard Method |
| Simple input clearing | Yes | Yes |
| Simulates keyboard behavior | No | Yes |
| Keyboard event testing | Limited | Better suited |
| Shortcut support | No | Yes |
60. Keyboard Actions with Explicit Wait
Dynamic elements should be synchronized before keyboard actions are performed.
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement search = wait.until(
ExpectedConditions.elementToBeClickable(
By.id("search")
)
);
new Actions(driver)
.click(search)
.sendKeys("Selenium")
.sendKeys(Keys.ENTER)
.perform();
61. Required Wait Imports
import java.time.Duration;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
62. Keyboard Actions with Dynamic Elements
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement input = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.cssSelector(".dynamic-input")
)
);
new Actions(driver)
.click(input)
.sendKeys("Dynamic Element")
.perform();
63. Keyboard Actions with iframe
If the target element is inside an iframe, Selenium must switch to that frame before performing keyboard actions on the element.
driver.switchTo().frame("loginFrame");
WebElement username = driver.findElement(
By.id("username")
);
new Actions(driver)
.click(username)
.sendKeys("testuser")
.perform();
driver.switchTo().defaultContent();
64. Keyboard Actions in Nested Frames
driver.switchTo().frame("outerFrame");
driver.switchTo().frame("innerFrame");
WebElement input = driver.findElement(
By.id("input")
);
new Actions(driver)
.click(input)
.sendKeys("Test Data")
.perform();
driver.switchTo().defaultContent();
65. Keyboard Actions with Browser Windows
Keyboard actions operate within the currently active browser window or tab. Selenium must switch to the required window before interacting with its elements.
driver.switchTo().window(windowHandle);
new Actions(driver)
.sendKeys(Keys.TAB)
.perform();
66. Keyboard Actions with Alerts
JavaScript alerts are handled through Selenium's Alert API rather than normal WebElement keyboard actions.
Alert alert = driver.switchTo().alert();
alert.sendKeys("Test Input");
alert.accept();
67. Alert Import
import org.openqa.selenium.Alert;
68. Keyboard Actions and Browser Shortcuts
Some browser-level shortcuts can behave differently across browsers, operating systems, browser configurations, or security restrictions. Application-level keyboard interactions should generally be the focus of automated tests.
69. Keyboard Actions on Focused Elements
When Actions.sendKeys() is used without explicitly clicking an element, the active element or current browser context receives the keyboard input.
new Actions(driver)
.sendKeys("Hello")
.perform();
70. Why Focus Matters?
Keyboard events depend heavily on focus. If the wrong element is focused, the keyboard action may be sent to an unexpected control.
- Click the required element when appropriate.
- Use Tab navigation when testing keyboard workflows.
- Verify the active element for complex applications.
- Avoid assuming focus is always correct.
71. Checking Active Element
JavaScript can be used to inspect which element currently has focus.
JavascriptExecutor js =
(JavascriptExecutor) driver;
WebElement activeElement =
(WebElement) js.executeScript(
"return document.activeElement;"
);
System.out.println(
activeElement.getAttribute("id")
);
72. Keyboard Navigation Test
A keyboard navigation test can verify whether focus moves through a form in the expected order.
WebElement username = driver.findElement(
By.id("username")
);
new Actions(driver)
.click(username)
.sendKeys("testuser")
.sendKeys(Keys.TAB)
.sendKeys("password")
.sendKeys(Keys.TAB)
.sendKeys(Keys.ENTER)
.perform();
73. Keyboard Actions for Accessibility Testing
Keyboard automation can help verify whether important application functions are reachable and usable through keyboard interaction.
- Tab navigation.
- Shift + Tab navigation.
- Enter activation.
- Space activation.
- Escape behavior.
- Arrow-key navigation.
- Keyboard-accessible menus.
- Keyboard-accessible dialogs.
74. Testing Tab Order
new Actions(driver)
.click(firstField)
.sendKeys(Keys.TAB)
.sendKeys(Keys.TAB)
.sendKeys(Keys.TAB)
.perform();
75. Keyboard Actions for Search Suggestions
WebElement search = driver.findElement(
By.id("search")
);
new Actions(driver)
.click(search)
.sendKeys("Selenium")
.pause(Duration.ofMillis(500))
.sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ENTER)
.perform();
76. Keyboard Actions for Calendar Navigation
Calendar widgets may use arrow keys to move between dates and Enter to select a date.
WebElement calendar = driver.findElement(
By.id("calendar")
);
new Actions(driver)
.click(calendar)
.sendKeys(Keys.ARROW_RIGHT)
.sendKeys(Keys.ARROW_RIGHT)
.sendKeys(Keys.ENTER)
.perform();
77. Keyboard Actions for Sliders
Accessible sliders may be controlled using arrow keys after the slider handle receives focus.
WebElement slider = driver.findElement(
By.cssSelector(".slider")
);
new Actions(driver)
.click(slider)
.sendKeys(Keys.ARROW_RIGHT)
.sendKeys(Keys.ARROW_RIGHT)
.sendKeys(Keys.ARROW_RIGHT)
.perform();
78. Keyboard Actions for Menus
WebElement menu = driver.findElement(
By.id("menu")
);
new Actions(driver)
.click(menu)
.sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ENTER)
.perform();
79. Keyboard Actions for Autocomplete Fields
WebElement input = driver.findElement(
By.id("location")
);
new Actions(driver)
.click(input)
.sendKeys("Mumbai")
.pause(Duration.ofMillis(500))
.sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ENTER)
.perform();
80. Keyboard Actions for Rich Text Editors
Rich text editors may support keyboard shortcuts for formatting, selection, indentation, and navigation.
WebElement editor = driver.findElement(
By.cssSelector("[contenteditable='true']")
);
new Actions(driver)
.click(editor)
.sendKeys("Important Text")
.keyDown(Keys.CONTROL)
.sendKeys("a")
.keyUp(Keys.CONTROL)
.perform();
81. Keyboard Actions with Pause
The pause() method can introduce a short delay inside an Actions sequence when a specific application interaction requires it.
new Actions(driver)
.click(searchBox)
.sendKeys("Selenium")
.pause(Duration.ofMillis(500))
.sendKeys(Keys.ENTER)
.perform();
82. Why Use Pause Carefully?
A fixed pause should not replace proper synchronization. Explicit waits are generally more appropriate when the application exposes a condition that can be observed.
83. Keyboard Actions and Thread.sleep()
Using arbitrary delays can make tests slower and less reliable.
Thread.sleep(3000);
new Actions(driver)
.sendKeys(Keys.ENTER)
.perform();
Prefer explicit waits when waiting for a known UI state.
84. Keyboard Actions with Assertions
After a keyboard interaction, the test should verify the resulting application state.
new Actions(driver)
.click(searchBox)
.sendKeys("Selenium")
.sendKeys(Keys.ENTER)
.perform();
WebElement result = new WebDriverWait(
driver,
Duration.ofSeconds(10)
).until(
ExpectedConditions.visibilityOfElementLocated(
By.id("results")
)
);
Assert.assertTrue(
result.isDisplayed(),
"Search results were not displayed"
);
85. Keyboard Actions with TestNG
@Test
public void verifySearchUsingKeyboard() {
WebElement search = driver.findElement(
By.id("search")
);
new Actions(driver)
.click(search)
.sendKeys("Selenium")
.sendKeys(Keys.ENTER)
.perform();
Assert.assertTrue(
driver.findElement(By.id("results"))
.isDisplayed()
);
}
86. TestNG Imports
import org.testng.Assert;
import org.testng.annotations.Test;
87. Keyboard Actions in Page Object Model
Keyboard interaction logic can be placed inside page objects so that test classes remain simple and readable.
public void searchUsingKeyboard(String text) {
WebElement search = driver.findElement(
By.id("search")
);
new Actions(driver)
.click(search)
.sendKeys(text)
.sendKeys(Keys.ENTER)
.perform();
}
88. Page Object Example
public class SearchPage {
private WebDriver driver;
private By searchBox = By.id("search");
private By results = By.id("results");
public SearchPage(WebDriver driver) {
this.driver = driver;
}
public void search(String text) {
WebElement search =
driver.findElement(searchBox);
new Actions(driver)
.click(search)
.sendKeys(text)
.sendKeys(Keys.ENTER)
.perform();
}
public boolean isResultDisplayed() {
return driver.findElement(results)
.isDisplayed();
}
}
89. Calling Page Object Method
@Test
public void verifySearch() {
SearchPage page =
new SearchPage(driver);
page.search("Selenium");
Assert.assertTrue(
page.isResultDisplayed()
);
}
90. Reusable Keyboard Utility
public class KeyboardUtils {
private WebDriver driver;
public KeyboardUtils(WebDriver driver) {
this.driver = driver;
}
public void pressEnter() {
new Actions(driver)
.sendKeys(Keys.ENTER)
.perform();
}
public void pressEscape() {
new Actions(driver)
.sendKeys(Keys.ESCAPE)
.perform();
}
public void pressTab() {
new Actions(driver)
.sendKeys(Keys.TAB)
.perform();
}
}
91. Reusable Shortcut Utility
public void ctrlA() {
new Actions(driver)
.keyDown(Keys.CONTROL)
.sendKeys("a")
.keyUp(Keys.CONTROL)
.perform();
}
public void ctrlC() {
new Actions(driver)
.keyDown(Keys.CONTROL)
.sendKeys("c")
.keyUp(Keys.CONTROL)
.perform();
}
public void ctrlV() {
new Actions(driver)
.keyDown(Keys.CONTROL)
.sendKeys("v")
.keyUp(Keys.CONTROL)
.perform();
}
92. Reusable Keyboard Navigation Utility
public void pressArrowDown(int count) {
Actions actions = new Actions(driver);
for (int i = 0; i < count; i++) {
actions.sendKeys(Keys.ARROW_DOWN);
}
actions.perform();
}
93. Platform-Specific Modifier Keys
Keyboard shortcuts can differ between operating systems. For example, Control is commonly used on Windows/Linux, while Meta is commonly used for many equivalent shortcuts on macOS.
Keys modifier = Keys.CONTROL;
new Actions(driver)
.keyDown(modifier)
.sendKeys("a")
.keyUp(modifier)
.perform();
94. Keyboard Actions and Browser Compatibility
Keyboard interactions should be validated on the browsers supported by the application because browser behavior and application event handling can vary.
| Browser | Keyboard Validation |
| Chrome | Keyboard navigation and shortcuts |
| Firefox | Keyboard navigation and shortcuts |
| Edge | Keyboard navigation and shortcuts |
95. Keyboard Actions and Responsive Applications
Keyboard interactions are generally less dependent on screen coordinates than mouse interactions, but focus behavior can still change depending on responsive layouts and application state.
96. Keyboard Actions and Dynamic UI
Modern JavaScript applications can dynamically replace elements. When this occurs, locate the current element before performing the keyboard action.
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement input = wait.until(
ExpectedConditions.elementToBeClickable(
By.id("dynamicInput")
)
);
new Actions(driver)
.click(input)
.sendKeys("Test")
.perform();
97. Common Keyboard Exceptions
NoSuchElementException
StaleElementReferenceException
ElementNotInteractableException
ElementClickInterceptedException
MoveTargetOutOfBoundsException
98. ElementNotInteractableException
This can occur when the target element is not currently available for interaction.
- Element is hidden.
- Element is disabled.
- Element is outside the required application state.
- Another element is blocking it.
- The page has not completed the required loading.
99. StaleElementReferenceException
A stale element can occur when the DOM changes after an element was located. Re-locate the current element before performing the keyboard action.
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement input = wait.until(
ExpectedConditions.refreshed(
ExpectedConditions.elementToBeClickable(
By.id("input")
)
)
);
new Actions(driver)
.click(input)
.sendKeys("Test")
.perform();
100. Keyboard Actions Troubleshooting
When a keyboard interaction fails, check the following areas:
- Verify the element locator.
- Verify that the element is visible.
- Verify that the element is enabled.
- Check whether the correct iframe is selected.
- Check whether the element has keyboard focus.
- Verify that no overlay is blocking the element.
- Wait for dynamic content when required.
- Confirm the correct modifier key for the operating system.
- Validate the application result.
101. Keyboard Actions Best Practices
- Use the
Actions class for advanced keyboard sequences.
- Use
WebElement.sendKeys() for simple text input when appropriate.
- Use stable locators.
- Ensure the correct element has focus.
- Use explicit waits for dynamic elements.
- Release modifier keys with
keyUp().
- Avoid unnecessary hard-coded delays.
- Validate the result after keyboard interaction.
- Keep reusable keyboard operations inside utilities.
- Keep page-specific locators inside page objects.
- Test keyboard workflows across supported browsers.
- Include keyboard accessibility scenarios where relevant.
102. Common Mistakes
- Sending keys without verifying which element has focus.
- Forgetting to release a modifier key.
- Using incorrect platform-specific shortcuts.
- Using
Thread.sleep() unnecessarily.
- Ignoring dynamic element changes.
- Not switching into the correct iframe.
- Assuming every custom component follows standard keyboard behavior.
- Not validating the final UI state.
- Duplicating keyboard action code across test classes.
- Using keyboard shortcuts when a simpler element interaction is more appropriate.
103. Keyboard Actions vs JavaScript
| Aspect | Keyboard Actions | JavaScript |
| Simulates user keyboard interaction | Yes | Not necessarily |
| Keyboard event testing | Suitable | Usually less suitable |
| Focus behavior | Can be tested | Can be manipulated directly |
| Realistic user interaction | Higher | Depends on implementation |
| Application keyboard shortcuts | Suitable | Usually not preferred |
104. Keyboard Actions with Screenshots on Failure
try {
new Actions(driver)
.click(searchBox)
.sendKeys("Selenium")
.sendKeys(Keys.ENTER)
.perform();
} catch (Exception e) {
File screenshot =
((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
System.out.println(
"Keyboard action failed: " + e.getMessage()
);
}
105. Screenshot Imports
import java.io.File;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
106. Logging Keyboard Actions
System.out.println("Clicking search box");
new Actions(driver)
.click(searchBox)
.perform();
System.out.println("Entering search text");
new Actions(driver)
.sendKeys("Selenium")
.perform();
System.out.println("Pressing Enter");
new Actions(driver)
.sendKeys(Keys.ENTER)
.perform();
107. Practical Login Keyboard Scenario
Consider a login form where the tester wants to enter the username, move to the password field using Tab, and submit the form using Enter.
- Open the login page.
- Locate the username field.
- Click the username field.
- Enter the username.
- Press Tab.
- Enter the password.
- Press Enter.
- Wait for the dashboard.
- Validate successful login.
108. Practical Login Example
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement username = wait.until(
ExpectedConditions.elementToBeClickable(
By.id("username")
)
);
new Actions(driver)
.click(username)
.sendKeys("testuser")
.sendKeys(Keys.TAB)
.sendKeys("Password123")
.sendKeys(Keys.ENTER)
.perform();
WebElement dashboard = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("dashboard")
)
);
Assert.assertTrue(
dashboard.isDisplayed(),
"Dashboard was not displayed"
);
109. Practical Search Scenario
Automate a product search using only keyboard interaction after focusing the search field.
WebElement search = driver.findElement(
By.id("productSearch")
);
new Actions(driver)
.click(search)
.sendKeys("Laptop")
.sendKeys(Keys.ENTER)
.perform();
WebElement results = new WebDriverWait(
driver,
Duration.ofSeconds(10)
).until(
ExpectedConditions.visibilityOfElementLocated(
By.id("searchResults")
)
);
Assert.assertTrue(results.isDisplayed());
110. Practical Form Navigation Scenario
WebElement firstName = driver.findElement(
By.id("firstName")
);
new Actions(driver)
.click(firstName)
.sendKeys("John")
.sendKeys(Keys.TAB)
.sendKeys("Doe")
.sendKeys(Keys.TAB)
.sendKeys("[email protected]")
.sendKeys(Keys.TAB)
.sendKeys("1234567890")
.perform();
111. Practical Dropdown Scenario
WebElement country = driver.findElement(
By.id("country")
);
new Actions(driver)
.click(country)
.sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ENTER)
.perform();
112. Practical Keyboard Accessibility Scenario
Test whether a user can navigate through important controls without relying on mouse clicks.
new Actions(driver)
.sendKeys(Keys.TAB)
.sendKeys(Keys.TAB)
.sendKeys(Keys.TAB)
.sendKeys(Keys.ENTER)
.perform();
113. Practical Mini Project
Project: Keyboard-Based Login and Search Automation
Create an automation flow where the user logs into a web application using keyboard navigation and then performs a search using the keyboard.
- Launch Chrome.
- Open the application.
- Wait for the username field.
- Enter username.
- Press Tab.
- Enter password.
- Press Enter.
- Wait for the dashboard.
- Locate the search field.
- Enter the search keyword.
- Press Enter.
- Wait for search results.
- Validate the result.
- Capture a screenshot if the test fails.
114. Complete Mini Project Example
@Test
public void verifyKeyboardLoginAndSearch() {
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement username = wait.until(
ExpectedConditions.elementToBeClickable(
By.id("username")
)
);
new Actions(driver)
.click(username)
.sendKeys("testuser")
.sendKeys(Keys.TAB)
.sendKeys("Password123")
.sendKeys(Keys.ENTER)
.perform();
WebElement dashboard = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("dashboard")
)
);
Assert.assertTrue(
dashboard.isDisplayed(),
"Dashboard was not displayed"
);
WebElement search = wait.until(
ExpectedConditions.elementToBeClickable(
By.id("search")
)
);
new Actions(driver)
.click(search)
.sendKeys("Selenium")
.sendKeys(Keys.ENTER)
.perform();
WebElement results = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("results")
)
);
Assert.assertTrue(
results.isDisplayed(),
"Search results were not displayed"
);
}
115. Sample Test Cases
| Test Case ID | Scenario | Expected Result |
| TC-KEY-001 | Press Enter in search field | Search is submitted |
| TC-KEY-002 | Navigate using Tab | Focus moves to the next control |
| TC-KEY-003 | Use Shift + Tab | Focus moves to the previous control |
| TC-KEY-004 | Use Escape on modal | Modal closes when supported |
| TC-KEY-005 | Use Arrow keys in dropdown | Option navigation works |
| TC-KEY-006 | Use Ctrl+A | Text is selected |
| TC-KEY-007 | Use keyboard form navigation | Focus moves correctly |
| TC-KEY-008 | Submit login with Enter | Login is submitted |
| TC-KEY-009 | Use keyboard on accessible control | Control responds correctly |
| TC-KEY-010 | Keyboard shortcut | Application performs expected shortcut action |
116. Keyboard Action Test Case Template
Test Case ID: TC-KEY-001
Title: Verify Keyboard Action
Precondition: Application is available
Steps:
1. Open the application
2. Locate the required element
3. Give focus to the element
4. Perform the required keyboard action
5. Continue the keyboard sequence
6. Validate the application response
Expected Result:
The application should respond correctly to
the specified keyboard interaction.
117. Interview Question: What are Keyboard Actions in Selenium?
Keyboard Actions are advanced keyboard interactions used to simulate keys, keyboard shortcuts, navigation, text selection, form submission, and other keyboard-based user interactions in Selenium WebDriver.
118. Interview Question: Which Class is Used for Keyboard Actions?
The org.openqa.selenium.interactions.Actions class is commonly used for advanced keyboard interactions.
119. Interview Question: Which Class Represents Keyboard Keys?
The org.openqa.selenium.Keys class provides constants representing special keyboard keys such as Enter, Tab, Shift, Control, Escape, and Arrow keys.
120. Interview Question: Difference Between keyDown() and keyUp()?
keyDown() presses and holds a modifier key, while keyUp() releases that modifier key.
new Actions(driver)
.keyDown(Keys.CONTROL)
.sendKeys("a")
.keyUp(Keys.CONTROL)
.perform();
121. Interview Question: How do You Press Enter?
new Actions(driver)
.sendKeys(Keys.ENTER)
.perform();
122. Interview Question: How do You Press Tab?
new Actions(driver)
.sendKeys(Keys.TAB)
.perform();
123. Interview Question: How do You Perform Ctrl+A?
new Actions(driver)
.keyDown(Keys.CONTROL)
.sendKeys("a")
.keyUp(Keys.CONTROL)
.perform();
124. Interview Question: How do You Perform Copy and Paste?
new Actions(driver)
.keyDown(Keys.CONTROL)
.sendKeys("c")
.keyUp(Keys.CONTROL)
.keyDown(Keys.CONTROL)
.sendKeys("v")
.keyUp(Keys.CONTROL)
.perform();
125. Interview Question: Why is Focus Important?
Keyboard events are delivered according to the active focus context. If the wrong element is focused, the keyboard action may be applied to the wrong control.
126. Interview Question: Can Actions Perform Keyboard and Mouse Actions Together?
Yes. The Actions class can combine mouse and keyboard operations into a single action sequence.
new Actions(driver)
.moveToElement(element)
.click()
.keyDown(Keys.CONTROL)
.sendKeys("a")
.keyUp(Keys.CONTROL)
.sendKeys("New Text")
.perform();
127. Interview Question: What is perform()?
The perform() method executes the built Actions sequence.
new Actions(driver)
.sendKeys(Keys.ENTER)
.perform();
128. Quick Revision
- Keyboard Actions automate keyboard-based browser interactions.
- The Selenium
Actions class supports advanced keyboard sequences.
- The
Keys class provides keyboard key constants.
- Use
sendKeys() to send text or special keys.
- Use
keyDown() to press and hold a modifier.
- Use
keyUp() to release a modifier.
- Use
Keys.ENTER for Enter.
- Use
Keys.TAB for Tab.
- Use
Keys.ESCAPE for Escape.
- Use
Keys.ARROW_DOWN and other arrow keys for navigation.
- Use Control or Meta depending on the platform and application shortcut.
- Use explicit waits for dynamic elements.
- Verify focus before performing complex keyboard interactions.
- Validate the final application state.
129. Keyboard Actions Checklist
- Required element identified.
- Stable locator used.
- Element is visible.
- Element is interactable.
- Correct iframe selected if required.
- Correct element has focus.
- Actions object created.
- Required keyboard key selected.
- Modifier key pressed where required.
- Keyboard action performed.
- Modifier key released.
- Application response validated.
- Explicit wait used for dynamic behavior.
- Screenshot captured for important failures.
- Reusable keyboard utility used where appropriate.
130. Best Keyboard Automation Workflow
Launch Browser
↓
Open Application
↓
Locate Element
↓
Wait Until Ready
↓
Give Element Focus
↓
Create Actions Object
↓
Press Required Key
↓
Use Modifier if Required
↓
Release Modifier
↓
Perform Action
↓
Wait for UI Response
↓
Validate Result
131. Conclusion
Keyboard Actions are an important part of Selenium WebDriver automation because many modern web applications depend on keyboard navigation, shortcuts, form submission, text editing, dropdown navigation, dialogs, menus, sliders, and accessibility features.
The Selenium Actions class provides powerful methods such as sendKeys(), keyDown(), keyUp(), click(), and other interaction methods that can be combined to create realistic keyboard workflows.
Reliable keyboard automation should use stable locators, correct focus management, explicit waits for dynamic elements, proper modifier-key handling, iframe switching when required, and assertions that verify the actual application result.
Recommended Selenium Learning Resources:
Selenium Training Course | Register for Course Demo