1

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?

cbdeveloper
  • 27,898
  • 37
  • 155
  • 336

2 Answers2

2

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.

stacks
  • 349
  • 2
  • 5
  • 13
  • Thanks, but does it mean the the `event.key` values as strings are not consistent? – cbdeveloper Apr 15 '20 at 18:30
  • You're welcome :) I do not know about that, you can figure it out by running your project on different browsers. But the question is : why use strings? You have keycodes that are 100% cross-browsers, so you may want to use those instead. – stacks Apr 15 '20 at 18:31
  • that would be for better readability. But I'll run some tests! Thanks again! – cbdeveloper Apr 15 '20 at 18:36
  • Hi, after further testing, this does not work for mobile. The W3 testing tool show `code 229` for basically every digits, comma or point. Take a look at: https://stackoverflow.com/questions/61248020/best-way-to-detect-typed-key-on-different-systems-and-keyboards – cbdeveloper Apr 16 '20 at 10:34
1

Across most browsers it should work just fine.

The names are a W3 standard:

https://www.w3.org/TR/uievents-key/#named-key-attribute-values

But you won't be able to read event.key or event.keyCode in Mobile Chrome for Android.

There is a Chromium bug on this.

Long discussion in https://bugs.chromium.org/p/chromium/issues/detail?id=118639

cbdeveloper
  • 27,898
  • 37
  • 155
  • 336
  • The return value of Event.key differs for example for the arrow keys in modern browsers like chrome `ArrowUp` and old browsers like IE11 `Up`. Is it now best practice to query both spellings? – KreutzerCode Sep 17 '22 at 15:51