5

I have this piece of code:

window.addEventListener('keydown', function (e) { 
   console.log(e.which); 
   console.log(e.keyCode); 
});

 var evObj = new KeyboardEvent('keydown', {key:65});
 window.dispatchEvent(evObj);

Why i see 0 in console and not 65 ??

Also both e.keyCode and e.which are 0 and not 65, i am on Chrome latest version

thank you a lot.

itsme
  • 48,972
  • 96
  • 224
  • 345
  • 2
    I tried google `javascript keyevent chrome`, it should be a bug from [this](https://bugs.webkit.org/show_bug.cgi?id=16735). The link is from [Post](http://stackoverflow.com/a/1897491/1737627). – fuyushimoya Aug 03 '15 at 10:44
  • If you only need Chrome as you commented elsewhere, this is a duplicate of [this question](http://stackoverflow.com/questions/6157929/how-to-simulate-a-mouse-click-using-javascript) which has a working answer. – T.J. Crowder Aug 03 '15 at 10:51
  • `Object.defineProperty(evObj , "which", {"value" : 666})` will overwrite the which as a workaround. – Mouser Aug 03 '15 at 10:53

3 Answers3

5

There is a bug in chrome, keyCode and which are not configurable.

Possible workarkaround: define a custom getter

 window.addEventListener('keydown', function (e) { console.log(e.which); });
 
 (function(o,k){
    //use createEvent for better compatibility
   var evObj = document.createEvent('HTMLEvents');
    evObj.initEvent('keydown', true, false);
    Object.defineProperty(evObj, 'keyCode', {
      get: function() {
        return k;
      }
    });
    Object.defineProperty(evObj, 'which', {
      get: function() {
        return k;
      }
    });
    o.dispatchEvent(evObj); 
 }(window,65));
Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
  • Yeah, **just** found that [in this answer](http://stackoverflow.com/a/6158050/157247). – T.J. Crowder Aug 03 '15 at 10:50
  • But does this means i triggered the correct specified keyboard button !? – itsme Aug 03 '15 at 10:56
  • It means you the `which`/`keyCode` -properties of the event will return the desired value(65) – Dr.Molle Aug 03 '15 at 11:01
  • @Dr.Molle but other than that i need it to really trigger the key ... :D – itsme Aug 03 '15 at 11:03
  • 2
    It really triggers the event, as long as "trigger" means that the listeners will be executed(otherwise you wouldn't see the 65 in the console). When you want something similar to [`sendKeys`](https://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys%28v=vs.110%29.aspx) that's a completely different question. – Dr.Molle Aug 03 '15 at 11:25
4

Also both e.keyCode and e.which are 0 and not 65, i am on Chrome latest version

Because you're setting key, not keyCode and which. According to MDN, key is a representation of the key, not a keycode. To initialize keyCode and/or which, you should...do that (see MDN's article on KeyboardEvent).

var evObj = new KeyboardEvent('keydown', {keyCode:65, which:65});

Here's an example, but it doesn't appear to work in Chrome (still get 0) — that's a Chrome bug, workaround below. Does work in Firefox. Fails in IE11 because IE11 doesn't like new KeyboardEvent:

window.addEventListener("keydown", function(e) {
  snippet.log("keyCode = " + e.keyCode + ", which = " + e.which);
}, false);
setTimeout(function() {
  var evObj = new KeyboardEvent('keydown', {keyCode:65, which:65});
  snippet.log("Sending event");
  window.dispatchEvent(evObj);
}, 300);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

You can work around the Chrome bug using the technique from this answer:

window.addEventListener("keydown", function(e) {
  snippet.log("keyCode = " + e.keyCode + ", which = " + e.which);
}, false);
setTimeout(function() {
  var evObj = new KeyboardEvent('keydown', {keyCode:65, which:65});
  // Chrome bug workaround:
  if (evObj.keyCode != 65) {
    Object.defineProperty(evObj, "keyCode", {
      value: 65
    });
    Object.defineProperty(evObj, "which", {
      value: 65
    });
  }
  snippet.log("Sending event");
  window.dispatchEvent(evObj);
}, 300);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • @T.J.Crowder thanks man a lot! shouldn't i accept the Dr.Molle answer? – itsme Aug 03 '15 at 11:02
  • 1
    @sbaaaang: Whichever you like, it's totally up to you. The above is not derived from Dr.Molle's answer. It *is* derived from [the other answer I linked to](http://stackoverflow.com/a/6158050/157247), which is elsewhere here on SO. (I found it when I was looking to find out why Chrome wasn't working.) – T.J. Crowder Aug 03 '15 at 11:15
-1

Note: In Firefox, the keyCode property does not work on the onkeypress event (will only return 0). For a cross-browser solution, use the which property together with keyCode, e.g:

var x = event.which || event.keyCode;  // Use either which or keyCode, depending on browser support