Use the Keyboard Lock API to capture the Escape key in full screen mode.
If you've ever played a full screen web game that popped up an in-game dialog that you instinctively canceled with the Escape key, you probably found yourself kicked out of full screen mode. This frustrating experience is caused by the fact that dialog and full screen mode "fight" for the Escape key. It's an unequal battle because, by default, full screen mode always wins. But how can you make the dialog the winner for the Escape key? This is where the Keyboard Lock API comes into play.
Browser support
Use the Keyboard Lock API
The Keyboard Lock API is available on navigator.keyboard.
The
lock()
method of
the Keyboard
interface
returns a promise after enabling the capture of key presses for any or all of the
keys on the physical keyboard. This method can only capture keys that are
granted access by the underlying operating system. Luckily the Escape key is
one of them.
If your app has a full screen mode, use the Keyboard Lock API as a progressive
enhancement by capturing the Escape key when requesting full screen. Unlock
(that is, no longer capture) the keyboard when leaving full screen mode using the
unlock()
method
of the Keyboard
interface.
// 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']);
console.log('Keyboard locked.');
return;
}
navigator.keyboard.unlock();
console.log('Keyboard unlocked.');
});
}
This means that when the user is in full screen mode, pressing Escape cancels the dialog per default. If the user presses and holds the Escape key, they can still exit full screen mode. The best of both worlds.
Demo
You can test both the default and the progressively enhanced variants in the demo. The demo's source code is less clean than the snippet before, because it needs to show both behaviors.
In practice
To use this progressive enhancement in practice, just copy the previous snippet. It's designed to work with no required changes, even with existing full screen code. As an example see this PR for the game Freeciv. Once the PR is merged, you can cancel all in-game dialogs by pressing Escape.
A bonus bookmarklet
Not all apps or games that support full screen mode will be open-source or accept your patches, the following bookmarklet can be added to your bookmarks bar and clicked to enable better full screen mode.