Q22 of 37 · Selenium

How do you simulate keyboard shortcuts in Selenium?

SeleniumMidseleniumkeyboardactionsshortcuts

Short answer

Short answer: Use the Actions class with `keyDown` / `keyUp` / `sendKeys` to model modifier+key combinations. `Actions.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform()` is the canonical Ctrl+A. On macOS, swap CONTROL for COMMAND.

Detail

Single keys are easy — element.sendKeys(Keys.ENTER) or Keys.TAB. Modifier-based shortcuts (Ctrl+S, Cmd+K, Shift+click) need the Actions class because you have to hold a key while sending another.

The canonical pattern:

new Actions(driver)
    .keyDown(Keys.CONTROL)
    .sendKeys("k")
    .keyUp(Keys.CONTROL)
    .perform();

keyDown and keyUp push and release the modifier; sendKeys types the regular key while the modifier is held. The pairing is critical — if you forget keyUp, subsequent typing happens with the modifier still held.

OS-aware shortcuts: macOS uses Cmd (Keys.COMMAND) where Windows/Linux uses Ctrl. Real-world shortcuts handlers often listen for the platform-correct key, so write a small helper:

Keys cmd = System.getProperty("os.name").toLowerCase().contains("mac")
    ? Keys.COMMAND : Keys.CONTROL;

Targeting: Actions sends events to the focused element. If the shortcut needs to fire on a specific input, click the input first to focus it, then run the Actions sequence.

Common shortcuts in the wild:

  • Ctrl/Cmd + A — select all.
  • Ctrl/Cmd + K — open command palette / search.
  • Shift + Click — multi-select in lists / tables.
  • Ctrl/Cmd + Enter — submit forms / send messages.

Edge case: some browser-level shortcuts (Ctrl + T to open a new tab, Ctrl + W to close) are intercepted by the browser and never reach the page. Selenium can't override that — those shortcuts have to be tested via the WebDriver window-management API instead.

// EXAMPLE

// Open the command palette with Cmd/Ctrl + K
Keys cmdOrCtrl = System.getProperty("os.name").toLowerCase().contains("mac")
    ? Keys.COMMAND : Keys.CONTROL;

new Actions(driver)
    .keyDown(cmdOrCtrl)
    .sendKeys("k")
    .keyUp(cmdOrCtrl)
    .perform();

// Type the search and submit
driver.switchTo().activeElement().sendKeys("Settings", Keys.ENTER);

// WHAT INTERVIEWERS LOOK FOR

Actions + keyDown/keyUp pattern, OS-aware modifier choice, and awareness that browser-intercepted shortcuts (Ctrl+T) can't be sent through Selenium.

// COMMON PITFALL

Forgetting keyUp and leaving the modifier held — every subsequent sendKeys looks broken until you teardown the driver. Or sending Ctrl on macOS for shortcuts that listen for Cmd.