detect keyboard layout with javascript

Parzifal picture Parzifal · Jan 17, 2012 · Viewed 26.4k times · Source

Is there any way to detect the current keyboard layout using JavaScript? I found this, but it only detects if the visitor is on the english layout. I need to know the exact layout as a string, e.g.de-ch, fr or en.

Answer

Nathaniel picture Nathaniel · Oct 10, 2012

I know this question is old, but for those of you who have been stymied by the fact that some keys map to different characters in other locales, here is an approach you can use to deal with it.

Most likely, you have your keyboard event handler tied to a keyup or keydown event; the results of the event.which or event.keyCode property in this case is tied to which key the user pressed. For instance, the same key you use to type ';' in an EN layout is the key used to type 'ж' in an RU layout, and the event reports 186 as the code for both of them.

However, if you're more interested in the character that resulted from the key press, you should use the 'keypress' event instead. This event fires after keydown/up, and it reports the actual unicode codepoint of the character that was typed inside event.which or event.charCode, which in the example above is decimal 1078 or U+0436.

So, if you'd prefer not to guess at keyboard layouts and you don't need to differentiate between keyup/keydown, keypress may be a viable alternative for you. It's not perfect (most browsers don't consistently report keypress events on keys that don't print characters, like modifier keys, function keys and navigation keys), but it's better than guessing at keycodes when dealing with printable characters.