Vim-style browser extensions (Vimium, Vimium C, Surfingkeys, Tridactyl) bind
plain letters: j scrolls, f shows link hints, x closes the tab. A focused
<canvas> looks like any other page to them, so a web game that uses those keys
loses them. The extensions do let keys through in one case: when the focused
element is editable, they switch to insert mode. trapKeys(canvas) makes the
canvas count as editable.
Who sees a key first
An extension’s content script handles a keystroke before the page’s own
handlers do, so preventDefault on keydown comes too late. Per-site exclusion
lists work, but each player has to set one up, and they break when the game runs
in an itch.io iframe on a CDN domain.
The trap
trapKeys sets contenteditable="true" on the element, along with
spellcheck="false", autocapitalize="off", inputmode="none" (no virtual
keyboard on phones) and tabindex="0" when the element has none. It hides the
caret and the focus outline.
An editable element also accepts editing, so the trap cancels beforeinput,
paste, cut, drop and compositionstart, and clears any selection that
lands inside the element. It never touches keydown or keyup: those are the
game’s. release() puts back every attribute and style it changed.
Escape
Esc is how a player leaves insert mode, so the extension keeps it, and the canvas loses focus. Without help, the next key would go to the extension again.
The refocus option decides when the trap takes focus back. 'always' (the
default) refocuses on any blur, which suits a page that is only the game.
'gated' refocuses only when focus fell to <body>, so links and chat inputs
elsewhere on the page keep working. 'manual' leaves it to the caller. Because
the game never receives Esc, a web build needs another pause key.
Tested
The end-to-end tests load each extension built from a pinned upstream commit
and type with trusted input (CDP or WebDriver, never dispatchEvent). Each run
first proves the extension works on a page without the trap, then checks the trap and
recovery after Esc. Vimium, Vimium C and Surfingkeys pass in Chromium; the
Tridactyl and Firefox find-as-you-type runs are still pending. EndWise and
CELLAGA ship with the trap.