0

Example here http://jsbin.com/yiyozepezi/edit?js,output

I am trying to generate some key events from within JavaScript, no jQuery. I want to trigger some events from my tests to make the code in the app react and do different things depending on the key.

A div is catching the event and printing some feedback:

document.getElementById("theFeedback").addEventListener("keydown", (event) => {
  console.log("KEYDOWN CAPTURED", event);
  
  let str = "";
  // have to manually enumerate fields as they are not enumerable
  ["code", "charCode", "keyCode", "key", "which", "altKey", "ctrlKey", "shiftKey"].forEach((k) => {
    console.log("str", str);
    str += `${k} = ${event[k]}<br>`;
  });

  document.getElementById("theFeedback").innerHTML = str;
});

And the button generates the event:

document.getElementById("theButton").addEventListener("click", () => {
  console.log("CLICK");

  let keyEvent = new KeyboardEvent("keydown", { keyCode: 61, altKey: false, shiftKey: false, key: "q" });
  document.getElementById("theFeedback").dispatchEvent(keyEvent);
});

EDIT Added code from a popular SO answer, but still no joy

document.getElementById("withKeyboardEvent").addEventListener("click", () => {
  console.log("CLICK KeyboardEvent");
  let keyEvent = document.createEvent("KeyboardEvent");
  let initMethod = typeof keyEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";
  keyEvent[initMethod](
                       "keydown",
                        true,      // bubbles oOooOOo0
                        true,      // cancelable   
                        window,    // view
                        false,     // ctrlKeyArg
                        false,     // altKeyArg
                        false,     // shiftKeyArg
                        false,     // metaKeyArg
                        61,  
                        0          // charCode   
    );
  document.getElementById("theFeedback").dispatchEvent(keyEvent);
});

and

document.getElementById("withPlainEvent").addEventListener("click", () => {
  console.log("CLICK withPlainEvent");
  let keyEvent = document.createEventObject ?
        document.createEventObject() : document.createEvent("Events");
  
    if(keyEvent.initEvent){
      keyEvent.initEvent("keydown", true, true);
    }
  
    keyEvent.keyCode = 61;
    keyEvent.which = 61;
    
    document.dispatchEvent ? document.dispatchEvent(eventObj) :     
                             document.fireEvent("onkeydown", eventObj); 
  document.getElementById("theFeedback").dispatchEvent(keyEvent);
});

The event is triggered and captured ok. But in Chrome / Safari, the caught event has no keyCode / which / etc. I have tried all sort of combinations (I understand the topic is quite messy, and some properties are read only).
It all works fine as it is in Firefox.
shiftKey, altKey and ctrlKey are ok on all browsers.
It all works fine as it is if I use a physical keyboard - but not in the JSBin demo (I think they have their own craziness going on)

Any idea what may make it work?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
gotofritz
  • 3,341
  • 1
  • 31
  • 47
  • Possible duplicate: https://stackoverflow.com/questions/8942678/keyboardevent-in-chrome-keycode-is-0/12522752#12522752 This seems to be a Webkit bug, which can be worked around by using a generic `Event` where you set the relevant properties – suluke Sep 14 '15 at 11:43
  • @suluke sadly not... I had seen that answer already, but it doesn't seem to help. I have added that code in my sample – gotofritz Sep 14 '15 at 12:54
  • how about this one: https://stackoverflow.com/questions/10455626/keydown-simulation-in-chrome-fires-normally-but-not-the-correct-key/10520017#10520017 Looks more sophisticated and the first comment indicates `it's the only working solution on SO` – suluke Sep 14 '15 at 16:35
  • 1
    The second code fragment `withPlainEvent` should be fixed to use `keyEvent` instead of `eventObj`, no? In the second to last line. If I change that in your jsbin I get 61 as `keycode` and `which` (Chrome 45, Linux) – suluke Sep 14 '15 at 16:47
  • You are right, thanks. Added updated link in question, it works with the "plainEvent" link. – gotofritz Sep 15 '15 at 06:54

0 Answers0