← Experiments

vimium-trap(archived)

Keep Vimium and friends from eating your web game's keyboard input.

npm install vimium-trap

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.

key jextensiongamescroll(a)
key jextensiongameinsert mode(b)
Figure 1 Where a keystroke goes. (a) The canvas has focus but is not editable: the extension's content script handles j and the page scrolls. (b) The focused canvas is editable: the extension stays in insert mode and passes j through to the game.

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.

Escblurnext framejlostrefocusgametime
Figure 2 Escape on a trapped canvas. The extension swallows Esc and the canvas loses focus. On the next animation frame the trap focuses it again, so the following key reaches the game; the Esc press itself never does.

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.