Handling Keyboard Events
Selenium’s Actions class and the sendKeys() method allow you to simulate various keyboard events.
This is useful for automation scenarios such as filling forms, submitting data, simulating hotkeys, and navigating through elements.
Common Keyboard Event Scenarios in Selenium
1. Typing Text
- Use case: Enter data into input fields.
WebElement input = driver.findElement(By.id("username"));
input.sendKeys("VinothQA");
2. Pressing Special Keys (e.g., ENTER, TAB, BACKSPACE)
- Use case: Submit a form, navigate fields, delete text.
input.sendKeys(Keys.ENTER);
input.sendKeys(Keys.TAB);
input.sendKeys(Keys.BACK_SPACE);
3. Keyboard Shortcuts (e.g., Ctrl+A, Ctrl+C, Ctrl+V)
- Use case: Select all, copy, paste.
import org.openqa.selenium.Keys;
import org.openqa.selenium.interactions.Actions;
Actions actions = new Actions(driver);
WebElement input = driver.findElement(By.id("textField"));
// Ctrl + A (Select All)
actions.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();
// Ctrl + C (Copy)
actions.keyDown(Keys.CONTROL).sendKeys("c").keyUp(Keys.CONTROL).perform();
// Ctrl + V (Paste)
actions.keyDown(Keys.CONTROL).sendKeys("v").keyUp(Keys.CONTROL).perform();
4. Simulating Key Combinations (SHIFT, ALT)
- Use case: Capitalizing text, accessing browser or app shortcuts.
// SHIFT + key for capital letter
actions.keyDown(Keys.SHIFT).sendKeys("v").keyUp(Keys.SHIFT).perform();
5. Clearing a Field
- Use case: Remove all existing text.
input.clear(); // Preferred method
// or with keyboard:
input.sendKeys(Keys.CONTROL + "a", Keys.DELETE);
6. Navigating Menus Using Arrow Keys
- Use case: Moving through dropdowns or lists.
input.sendKeys(Keys.ARROW_DOWN);
input.sendKeys(Keys.ARROW_UP);
7. Submitting a Form
- Use case: Submitting without clicking a button.
input.sendKeys(Keys.ENTER);
// or
input.submit();