Search code examples
javascriptreactjskeyboardcross-browserkeyboard-events

Are "KeyboardEvent.key" values consistent cross-browsers?


I'm building this component and I'm relying on event.key values in the onKeyDown handler to allow / disallow some inputs.

DOCS:

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values

const ALLOWED_KEYS = [
  "Ctrl", "Meta", "Shift","Home", "End", 
  "Backspace", "Delete", 
  "ArrowLeft", "ArrowRight", "Tab"
];

// ....

function onKeyDown(event) {
  if (ALLOWED_KEYS.indexOf(event.key) >= 0) {
    console.log("Allowed...");
  }
  else {
    event.preventDefault();
    console.log("NOT allowed...");
  }
}

Are those names consistent across browsers? Can I be sure that ArrowRight will be ArrowRight on Chrome, Edge, Firefox, Safari, etc? Or should I use some kind of key code value?


Solution

  • Here you have all the keycodes according to w3.org, which are cross browser. Those are the keycodes you want to use. You can type arrowLeft, right or backspace or whatever to find the corresponding keyvalue to that key.

    This tool is quite handy so you might save this link somewhere.