Careeroza
Keyboard Shortcuts
Keys and Key Combinations
import org.openqa.selenium.Keys;
WebElement search = driver.findElement(By.id("search"));
search.sendKeys("wireless mouse", Keys.ENTER);
// select all text and replace it
search.sendKeys(Keys.chord(Keys.CONTROL, "a"), "keyboard");
// Shift + type = capital letters, using Actions
new Actions(driver).keyDown(Keys.SHIFT).sendKeys(search, "usb").keyUp(Keys.SHIFT).perform();
System.out.println(search.getDomProperty("value"));Example
Output:
Run KeyboardTest.main()Example output
keyboardUSB
Cross-platform Shortcuts
Example
Ctrl on Windows/Linux is Command on macOS. A small helper chooses the right key; here it is simulated with the OS name as a parameter:
public class Main {
static String modifierFor(String osName) {
return osName.toLowerCase().contains("mac") ? "Keys.COMMAND" : "Keys.CONTROL";
}
public static void main(String[] args) {
for (String os : new String[] {"Windows 11", "Mac OS X", "Linux"}) {
System.out.println(os + " -> Keys.chord(" + modifierFor(os) + ", \"a\")");
}
}
}Output
Windows 11 -> Keys.chord(Keys.CONTROL, "a") Mac OS X -> Keys.chord(Keys.COMMAND, "a") Linux -> Keys.chord(Keys.CONTROL, "a")
Tip: In real code use Platform.getCurrent().is(Platform.MAC) or System.getProperty("os.name").