Better fullscreen mode with the Keyboard Lock API
The bad experience 👎
-
Click the button to go fullscreen:
-
Click the button to show the dialog:
- Cancel the dialog with the Esc key.
- You're kicked out of fullscreen mode.
The good experience 👍
-
Click the button to go fullscreen:
-
Click the button to show the dialog:
- Cancel the dialog with the Esc key.
-
Leave fullscreen mode by pressing and holding the Esc key.
Show me how 💡
Use the Keyboard Lock API as a progressive enhancement
// Feature detection.
const supportsKeyboardLock =
('keyboard' in navigator) && ('lock' in navigator.keyboard);
if (supportsKeyboardLock) {
document.addEventListener('fullscreenchange', async () => {
if (document.fullscreenElement) {
// The magic happens here… 🦄
await navigator.keyboard.lock(['Escape']);
return console.log('Keyboard locked.');
}
navigator.keyboard.unlock();
console.log('Keyboard unlocked.');
});
}