Keyboard
Keyboard API
Keyboard API
The **`Keyboard`** interface of the provides functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard.
A list of valid code values is found in the [UI Events KeyboardEvent code Values](https://w3c.github.io/uievents-code/) spec.
## Instance properties
_Also inherits properties from its parent interface, EventTarget._
## Instance methods
_Also inherits methods from its parent interface, EventTarget._
- Keyboard.getLayoutMap()
- : Returns a Promise that resolves with an instance of KeyboardLayoutMap which is a map-like object with functions for retrieving the strings associated with specific physical keys.
- Keyboard.lock()
- : Returns a Promise that resolves after enabling the capture of key presses for any or all of the keys on the physical keyboard.
- Keyboard.unlock()
- : Unlocks all keys captured by the `lock()` method and returns synchronously.
## Example
### Keyboard mapping
The following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'W' key on an English QWERTY keyboard.
```js
if (navigator.keyboard) {
const keyboard = navigator.keyboard;
keyboard.getLayoutMap().then((keyboardLayoutMap) => {
const upKey = keyboardLayoutMap.get("KeyW");
window.alert(`Press ${upKey} to move up.`);
});
} else {
// Do something else.
}
```
### Keyboard locking
The following example captures the <kbd>W</kbd>, <kbd>A</kbd>, <kbd>S</kbd>, and <kbd>D</kbd> keys by calling `lock()` with a list that contains the key code attribute value for each of these keys:
```js
navigator.keyboard.lock(["KeyW", "KeyA", "KeyS", "KeyD"]);
```
This captures these keys regardless of which modifiers are used with the key press. Assuming a standard United States QWERTY layout, registering `KeyW` ensures that <kbd>W</kbd>, <kbd>Shift+W</kbd>, <kbd>Control+W</kbd>, <kbd>Control+Shift+W</kbd>, and all other key modifier combinations with <kbd>W</kbd> are sent to the app. The same applies to `KeyA`, `KeyS`, and `KeyD`.
## Specifications
## Browser compatibility
Cite this
"Keyboard". MDN Web Docs. CC BY-SA 2.5 (MDN). https://developer.mozilla.org/en-US/docs/Web/API/Keyboard JSON record · API collection · BibTeX · RIS · CSL-JSON · citation policy