Reputation: 771
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.
Upvotes: 2
Views: 352
Reputation: 57651
It's a bit complicated indeed, mostly for historical reasons. Things are different depending on whether you are looking at keypress
or keydown
/keyup
events. The keypress
event works with character codes wherever possible. This means that for printable characters (the ones you can have in a text field) the charCode
parameter should be set while the keyCode
parameter is 0. The charCode
parameter is really the ASCII code of the character, meaning that in your case (letter w
) you would do:
evt.initKeyEvent("keypress", true, true, window, 0, true, 0, 0, 0, "w".charCodeAt(0));
For non-printable characters or when using the keydown
/keyup
events on the other hand you should set the keyCode
parameter and pass 0 as charCode
. This parameter refers to virtual key codes. The key code you would use here is DOM_VK_W
:
evt.initKeyEvent("keydown", true, true, window, 0, true, 0, 0, evt.DOM_VK_W, 0);
The constant DOM_VK_W
is only defined in Firefox however, for compatibility with other browsers you should use its numerical value:
evt.initKeyEvent("keydown", true, true, window, 0, true, 0, 0, 87, 0);
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 (handling keypress
) 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.
Upvotes: 4
Reputation: 7280
Looking through the pages that you reference you can either use the virtual key code defined in the second document:
94 const unsigned long DOM_VK_W = 0x57;
which would give the code
evt.initKeyEvent("keypress", true, true, window, 0, true, 0, 0, 87, 0);
or you could pass the character code (last argument), which is the same value:
evt.initKeyEvent("keypress", true, true, window, 0, true, 0, 0, 0, 87);
NB: I've not been able to test this and it is based on the documentation directly.
Upvotes: 0