Keydown Simulation in Chrome fires normally but not the correct key

dom-events, google-chrome, javascript

Solution

So very very close...

You just needed to override the 'which' property. Here's some sample code:

document.addEventListener('keydown', e => console.log(
'altKey                : ' + e.altKey + '\n' +
'charCode (Deprecated) : ' + e.charCode + '\n' +
'code                  : ' + e.code + '\n' +
'ctrlKey               : ' + e.ctrlKey + '\n' +
'isComposing           : ' + e.isComposing + '\n' +
'key                   : ' + e.key + '\n' +
'keyCode (Deprecated)  : ' + e.keyCode + '\n' +
'location              : ' + e.location + '\n' +
'metaKey               : ' + e.metaKey + '\n' +
'repeat                : ' + e.repeat + '\n' +
'shiftKey              : ' + e.shiftKey + '\n' +
'which (Deprecated)    : ' + e.which + '\n' +
'isTrusted             : ' + e.isTrusted + '\n' +
'type                  : ' + e.type
));

Podium = {};
Podium.keydown = function(k) {
  var oEvent = document.createEvent('KeyboardEvent');

  // Chromium Hack
  Object.defineProperty(
    oEvent,
    'keyCode',
    {
       get : function() {
         return this.keyCodeVal;
       }
    }
  );
  Object.defineProperty(
    oEvent,
    'which',
    {
       get : function() {
         return this.keyCodeVal;
       }
    }
  );

  if (oEvent.initKeyboardEvent) {
    oEvent.initKeyboardEvent("keydown", true, true, document.defaultView,
                             false, false, false, false, k, k);
  }
  else {
      oEvent.initKeyEvent("keydown", true, true, document.defaultView,
                          false, false, false, false, k, 0);
  }

  oEvent.keyCodeVal = k;

  if (oEvent.keyCode !== k) {
    alert("keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")");
  }

  document.dispatchEvent(oEvent);
}

//Sample usage
Podium.keydown(65);

Note: this code is not designed to work in IE, Safari, or other browsers. Well, maybe with Firefox. YMMV.

Problem

I want to simulate `keydown` events on a given textarea element in an html page. Since I am using Chrome, I called `initKeyboardEvent` on my variable and I passed the `keyCode` I want to type into the textarea. Here is what I tried: ``` var keyEvent = document.createEvent('KeyboardEvent'); keyEvent.initKeyboardEvent('keydown', true, false, null, 0, false, 0, false, 77, 0); inputNode.dispatchEvent(keyEvent); ``` In this code I'm typing the letter m however the textarea is only getting the `keyCode` 13 which is the Enter key. So, I tried an override code I saw online that sets the value to `keyCodeVal`, but with no success. ``` var keyEvent = document.createEvent('KeyboardEvent'); Object.defineProperty(keyEvent, 'keyCode', { get : function() { return this.keyCodeVal; } }); keyEvent.initKeyboardEvent('keydown', true, false, null, 0, false, 0, false, 77, 0); keyEvent.keyCodeVal = 77; inputNode.dispatchEvent(keyEvent); ``` Does anyone have an idea how to set the `keyCode` value?

Original source

Related problems