2

There are 2 properties for KeyboardEvent:

How to get key having code without having the event itself? So I only have the code value outside of the event and want to know what key is associated with it.

Jango
  • 115
  • 1
  • 8
  • This is like you asked how to use brakes of the car with wipers ... `key` and `code` are implementing totally different things, they're not interchangeable, thought [it looks like](https://stackoverflow.com/questions/67468091/find-out-keyboardevent-key-by-keyboardevent-code#comment119251029_67468155) you'd already knew this ..? – Teemu May 10 '21 at 10:00
  • The key is directly related to both the layout and the code. Knowing the layout, it should be possible to determine the key associated with a code. – Jango May 10 '21 at 10:04
  • Edwin has already answered how to connect the layout and the characters, but you deemed that being more or less impossible, which of course it is. It's notable, that the mapping is made on the OS level, but you can't access that map via JS. – Teemu May 10 '21 at 10:18

4 Answers4

5

It is impossible to reliably guess the key from the code, because the code refers to the physical key being pressed, while the value of key depends on the keyboard layout. For example on my german QWERTZ keyboard the key corresponding to the code 'BracketLeft' is 'ü' while on an american QWERTY keyboard it would be ']'.

If your goal is to tell your users which key to press to trigger some action you could try some other ways:

  • Create an image of a keyboard on which the key is highlighted and display that as a hint
  • Somehow get your users to press the key so you can observe the actual event and learn the appropiate key value that way
  • Create code -> key mappings for the keyboard layouts your users are most likely to use and guess the correct mapping depending on browser locale and/or observed keyboard events

None of these options are perfect but I think can get you pretty close.

seabeast
  • 181
  • 4
  • I predefine what code I expect to meet before the actual event happens. In the UI, I want to show the user what key in their keyboard layout will match the expected code. That's unfortunate, it seems there is no API to obtain client's keyboard layout :( – Jango May 10 '21 at 10:01
  • So if I understand correctly you want to display hints for keyboard shortcuts like 'Press x to do some action'? In that case I have added some alternatives which might help you. It's not perfect but I don't know any other way. – seabeast May 10 '21 at 11:15
1

I was trying to do the same thing as you, showing in the UI the current key values for the user that correspond to the KeyboardEvent.code (the physical key).

Short answer:

Not possible at the moment. It's probably better to use one of the suggestions made by @seabeast.

Long answer:

As today, there is a non-standardized way of getting this in Chrome based browsers: KeyBoardLayoutMap. Example from MDN:

window.addEventListener("keydown", function (e) {   
   const keyboard = navigator.keyboard;   
   keyboard.getLayoutMap().then((keyboardLayoutMap) => {
      const keyValue = keyboardLayoutMap.get(e.code);
      console.log(`code: ${e.code}  <->  key: ${e.key}  <->  result: ${keyValue}`);  
   }); 
});

This code would not be reliable for anything serious as keyboardLayoutMap.get() returns undefined for keys outside of the printable chars in the alphanumeric section. I've even found that in Chrome v93 is giving me swapped values for key < and º in a European Spanish layout.

My other failed attempt was to dispatch fake keyboard events before the user can do anything. The problem is you have to manually populate each property in the event object (i.e.: you have to know the code and key beforehand).

The specification says absolutely nothing about how the two might relate to each other in a consistent way.

Honestly not sure how a professional web app might be managing this kind of stuff, maybe as @seabeast said: an educated guess that connects the locale in window.navigator.language to a saved code->key map of its most common kb layout?

Conclusion:

If nothing of the previous suggestions satisfies you, you could always try to minimize confusion to the end-user. I'll probably:

  1. Stick to the event.key property.
  2. Give user the possibility to rebind the keys to his/her needs.
  3. And try not to get too much creative with your default shortcut set. Just using the common ASCII/English characters in the alphanumeric section and maybe some of the function section if needed.

The reason is that the user can usually link those key values representations in your UI to a physical key on his/her keyboard, and when that fails he/she can rebind the key.

40detectives
  • 350
  • 1
  • 3
  • 12
0

You may want to store an associative array of codes -> keys in a json file ? I dont see another solution

Edwin
  • 39
  • 4
  • 1
    KeyboardEvent.key depends on keyboard layout, while KeyboardEvent.code does not. It would require making associative array between codes and keys in all possible layouts, which is not a plausible solution. – Jango May 10 '21 at 09:51
  • indeed, my bad. – Edwin May 10 '21 at 09:55
-2

I hope that I got your question right, if so, I think your questions is answered here: Get Character value from KeyCode in JavaScript... then trim

The function you are looking for is this one i think:

String.fromCharCode(e.keyCode);
cj_loop
  • 57
  • 4
  • 1
    KeyboardEvent.keyCode is a different thing. By the way, it's deprecated. The question is not about it, just open the links I attached to the question. – Jango May 10 '21 at 09:45
  • This is a terrible suggestion as `String.fromCharCode` will mess up for lots of non-printable codes AND all the keys outside the ASCII range. Not feasible when we're trying to bypass with a friendly UI the fact that different keyboard layouts exist for the users in the wild. – 40detectives Sep 23 '21 at 23:46