Better fullscreen mode with the Keyboard Lock API

The bad experience 👎

  1. Click the button to go fullscreen:
  2. Click the button to show the dialog:
  3. Cancel the dialog with the Esc key.
  4. You're kicked out of fullscreen mode.

The good experience 👍

  1. Click the button to go fullscreen:
  2. Click the button to show the dialog:
  3. Cancel the dialog with the Esc key.
  4. 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.');
  });
}