views:

1529

answers:

1

I'm trying to simulate a keyboard event in Safari using JavaScript.

I have tried this:

var event = document.createEvent("KeyboardEvent");
event.initKeyboardEvent("keypress", true, true, null, false, false, false, false, 115, 0);

...and also this:

var event = document.createEvent("UIEvents");
event.initUIEvent("keypress", true, true, window, 1);
event.keyCode = 115;

After trying both approaches, however, I have the same problem: after the code has been executed, the keyCode/which properties of the event object are set to 0, not 115.

Does anyone know how to reliably create and dispatch a keyboard event in Safari? (I'd prefer to achieve it in plain JavaScript if possible.)

A: 

The Mozilla Developer Center provides the following explanation:

  1. Create an event using document.createEvent("KeyboardEvent")
  2. Init the keyevent using

    event.initKeyEvent (type, bubbles, cancelable, viewArg, ctrlKeyArg, altKeyArg, shiftKeyArg, metaKeyArg, keyCodeArg, charCodeArg)

  3. Dispatch the event

I don't see the last one in your code, maybe that's what you're missing. I hope this works in IE as well...

Javache
Unfortunately, this doesn't fix the problem.
Steve Harrison
I revised my whole answer, hope that helps.
Javache
Unfortunately, Mozilla's implementation is non-standard. As for point 3, my problem is creating the correct event—dispatching the event comes after this. Also, since I'm developing for Apple's Dashboard, I don't have to worry about IE at all! (Whoopee!)
Steve Harrison