views:

342

answers:

1

I'm trying to fire a keyboard event to a page using javascript on Chrome. I had an approach that used to work on Firefox:

pressKey = function(key, shift) {
  var evt = document.createEvent('KeyboardEvent');
  evt.initKeyEvent("keypress", false, true, null, false, false,
                   shift, false, keyCode(key), key.charCodeAt(0));
  document.dispatchEvent(evt);
}

where key is the desired key and keyCode changes lowercase letters into highercase and also calls charCodeAt().

My problem is that events on Safari/Chrome don't have initKeyEvent, but initKeyboardEvent. The main difference I could notice was that you have to pass the key as a keyIdentifier (which looks like a unicode character) instead of passing the keycode and the keychar. Nonetheless I still can't manage to make it work.

I've also tried the JQuery approach described here without success.

EDIT: I debugged this a little further and it seems that the event on Chrome does trigger the listeners, but keyCode/charCode is always 0. I've tried to set evt.keyCode or evt.charCode with no success either.

+2  A: 

I've tracked this down to a bug on Webkit where created events only contain KeyIdentifier but no keyCode/charCode as can be seen on the browser source code. There seems to be a patch going on to solve this. So I guess this is not a proper question anymore...

fserb
Remember to accept your own answer when you can
Ngu Soon Hui