1

I am attempting to create, via JavaScript, a KeyboardEvent that resembles as closely as possible one that would be created by the browser natively (e.g. when I press a key, the keyDown event fires. The event object associated with this event is what I'm attempting to reproduce).

The createEvent method can be used to create an event of a specific type:

var evt = document.createEvent("KeyboardEvent");

Then, the initKeyboardEvent method can be used to initialise the event object with some data. The signature of this method seems to vary wildly between browsers. I've got this working in Firefox, which uses the initKeyEvent method instead. As far as I've been able to make out, WebKit expects the following arguments:

evt.initKeyboardEvent(
    "keydown",          // The name of the event
    true,               // Whether it bubbles
    true,               // Whether it can be cancelled
    window,             // The `window` in which it is being fired
    "U+004A",           // The "key identifier" (this is an uppercase "J")
    0,                  // The "key location" (0 for the normal character keys)
    false,              // Whether the Control key was held
    false,              // Whether the Alt key was held 
    false,              // Whether the Shift key was held 
    false,              // Whether a meta key was held 
    false               // Whether the "Alt Graph" key was held?
);

There doesn't seem to be any way to pass a key code (in the keyCode or which properties). I have attempted to follow the WebKit source, but that hasn't helpd. The KeyboardEvent IDL definition appears to refer to a keyCode property (and a charCode property) but I've been unable to work out how that ever gets a value.

Relevant files from the WebKit source:

And here's a fiddle to demonstrate the issue. Open the console and a KeyboardEvent should be there to examine. That's the synthetic one. Notice how the keyCode and which properties have the value 0. If you focus the "Result" frame and press any key, you can examine a native event object to see the difference.

So, my question: is it possible to add a keyCode or which value to a synthetic KeyboardEvent object in WebKit, and if so, how can I do it?

James Allardice
  • 164,175
  • 21
  • 332
  • 312

0 Answers0