I’m attempting to simulate some keyboard keycodes (Alt + W) using initKeyEvent:
evt = document.createEvent("KeyboardEvent");
evt.initKeyEvent("keypress",true,true,window,0,true,0,0,?,?);
body.dispatchEvent(evt);
The problem is I can’t find the virtual key code value and Unicode character for w.
The Firefox key events are documented here but I can’t make any sense of it.
The initKeyEvent is specified here.
It’s a bit complicated indeed, mostly for historical reasons. Things are different depending on whether you are looking at
keypressorkeydown/keyupevents. Thekeypressevent works with character codes wherever possible. This means that for printable characters (the ones you can have in a text field) thecharCodeparameter should be set while thekeyCodeparameter is 0. ThecharCodeparameter is really the ASCII code of the character, meaning that in your case (letterw) you would do:For non-printable characters or when using the
keydown/keyupevents on the other hand you should set thekeyCodeparameter and pass 0 ascharCode. This parameter refers to virtual key codes. The key code you would use here isDOM_VK_W:The constant
DOM_VK_Wis only defined in Firefox however, for compatibility with other browsers you should use its numerical value:The virtual key codes are identical to ASCII codes for many characters, they are not the same thing however. In particular, virtual key codes refer to actual buttons being pressed on your keyboard so they don’t distinguish between lower-case and upper-case letters – this is irrelevant for key combinations like CtrlW which are handled on
keydown. On the other hand, text fields (handlingkeypress) very much care about this difference – here ASCII codes are used that indicate the actual character to be added.Note that both this approach (distinguishing between events for buttons being pressed on the keyboard and the actual characters that these buttons produce) and the actual virtual key codes have been “borrowed” from Windows.