Document.hasFocus() Gates Global Shortcuts

Global key handlers fire for every focused window, so document.hasFocus() gates shortcuts and stops a page from consuming keystrokes another window owns.

TypescriptResilience

Code

typescriptsnippet
19 lines
const shortcuts: Record<string, () => void> = {
  k: () => console.log('open command palette'),
  s: () => console.log('save draft'),
};

function onKeydown(event: KeyboardEvent): void {
  // Another window or app can own the OS focus; its keystrokes must stay there.
  if (!document.hasFocus()) return;

  const action = event.ctrlKey ? shortcuts[event.key] : undefined;
  if (action) {
    event.preventDefault();
    action();
  }
}

window.addEventListener('keydown', onKeydown);

console.log('document.hasFocus():', document.hasFocus());

What happens on each run — Document.hasFocus() Gates Global Shortcuts

Every step of the demo happens inside the function onKeydown.

Watch out for

  • Whatever the file imports comes from the standard library — nothing else.
  • The snippet leans on document, window — browser-only surfaces a bare Node process cannot provide.

Putting it to use

The entry-point signature is function onKeydown(event: KeyboardEvent)

The demo output is labeled (open command palette, save draft, document.hasFocus():); each label names the call that printed it.

Core lines

const shortcuts: Record<string, () => void> = {
  k: () => console.log('open command palette'),
  s: () => console.log('save draft'),
};
window.addEventListener('keydown', onKeydown);

Interactive Tools for This Topic

FAQ

Does Document.hasFocus() Gates Global Shortcuts run in plain Node.js?
No — it touches `document` and `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.