Translate Javascript keyCode into charCode for non-U.S. keyboard layout (i.e. azerty)

前端 未结 2 829
梦谈多话
梦谈多话 2020-12-24 09:32

Quick background:

  • when a key is pressed in a browser, three events are generated: keyDown, keyPress and keyUp
2条回答
  •  不思量自难忘°
    2020-12-24 10:05

    I have solved my own question. It's not a 100% solution but it should cover most of what is needed. Hopefully there will be a cleaner solution when browser vendors start integrating DOM Level 3 Events.

    Just to re-iterate the main constraints:

    1. The key down and key up events should be reported/sent at the time they actually happen. I.e. sending a key down and key up together during the keyPress event is insufficient.
    2. Many key combinations must be fully handled during the keyDown event either because they never trigger a keyPress event (i.e. Ctrl key) or because the default action must be stopped in keyDown (WebKit) and doing so prevents the keyPress event from happening.
    3. The key down and key events should report the translated character code and not keyCode value.

    Without some out-of-the-box epiphany, the current browser implementations appear to prevent all three constraints from being fulfilled completely. So I have decided to relax constraint #3 just a bit.

    • On browser keyDown event add the event to a key down list and check to see if it is a safe (no undesirable browser default behavior) key combination:

      • Safe: do nothing until the keyPress.

      • Unsafe: report/send a key down event immediately. This is where constraint #3 is relaxed because these limited key combinations are not translated to a character code (many of them don't have them though anyways).

    • On browser keyPress event (which happens immediately after the keyDown event) check to see if it is a safe key combination:

      • Safe: report/send a key down event. Update the key down list using the translated character code (event.which).

      • Unsafe: do nothing since it was already reported/sent during keyDown.

    • On browser keyUp event, find and remove the matching event from the key down list and use the translated code to report/send the key up event.

    Some additional links for those interesting:

    • The noVNC commit with the change.
    • Some wiki notes on the issues as related to noVNC.
    • This solution has been adopted in RedHat's Broadway project (HTML5 GTK+ backend).

提交回复
热议问题