Search code examples
javascriptgoogle-chromewebkit

Firing a keyboard event on Chrome


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.


Solution

  • I just want to throw this basic snippet out there. It works in Chrome and is based on the hack mentioned by Paul Irish.
    It uses charCode instead of keyCode (which can be useful in certain situation), but adapt to keyCode if you so please.

    var keyboardEvent = new KeyboardEvent('keypress', {bubbles:true}); 
    Object.defineProperty(keyboardEvent, 'charCode', {get:function(){return this.charCodeVal;}}); 
    keyboardEvent.charCodeVal = [your char code];
    document.body.dispatchEvent(keyboardEvent);