All challenges · Core Interactions
Challenge 12 of 29 · Building fluency · Core Interactions
Detect a Keyboard Press
Focus an input and send a key press, the way a keyboard user would. The hidden check reads what the page detected.
Skills you will practise
- focus
- key presses
- keyboard events
The concept
Keyboard events go to whichever element has focus. A user tabs to or clicks a field, then presses a key, and the browser dispatches keydown, keypress (for character keys) and keyup to that element. Playwright mirrors this. locator.press('Escape') focuses the element and sends the key; page.keyboard.press() sends it to whatever is focused right now.
Key names follow the standard KeyboardEvent.key values: Enter, Escape, ArrowDown, Tab, single characters like a, and combinations such as Shift+A or Control+S.
Testing keyboard behaviour is also accessibility testing. If a feature only works with a mouse, keyboard users are locked out.
The fragile version
await page.keyboard.press('a');Why it breaks: Nothing has been focused, so the key goes to the page body (or whatever happened to have focus) and the input never receives it.
A robust Playwright version
const field = page.getByRole('textbox', { name: 'Shortcut' });
await field.focus();
await page.keyboard.press('ArrowUp');
// or, in one step:
await field.press('ArrowUp');
await expect(page.getByText('Last key: ArrowUp')).toBeVisible();Focus is explicit, the key name is valid, and the assertion checks what the page reports.
This is a general example on a made-up page, not the challenge’s reference solution.
Common mistakes
- Pressing keys without focusing the target first.
- Using made-up key names like
'up'instead of'ArrowUp'. - Using
fill()when the page listens for individual key events; usepress()orpressSequentially().
FAQ
What is the difference between locator.press and page.keyboard.press?
locator.press focuses that element first; page.keyboard.press sends to the currently focused element.
How do I press a key combination?
Join keys with +, for example 'Control+A' or 'Shift+Tab'.
Does fill() trigger keydown events?
Not per character. Use pressSequentially() if the page reacts to each key.
Try it
Practise this in Challenge 12. You write the code in the browser editor with no setup. It runs in a fresh Chromium, a hidden validator checks what actually happened, and you get pass or fail, the logs and a video of the run. Create a free account to open the practice page and its hints. The reference solution and the hidden validator are shown only after you pass. We never publish solutions here.