0

I've created a function to programmatically send a KEYDOWN event.

If I open the developer console I can see that the event is successfully dispatch. I catch the event using this function:

document.addEventListener ('keydown', function () {
     console.log (JSON.stringify (event.keyCode))
}, false);

But if I click on an input text field and I programatically send the key value (for example) of the letter "W", the letter does not appear in it.

What am I doing wrong?

This is the function to programmatically dispatch the event:

function sendKeyDownEvent (keyCode) {
     var e = new Event ("keydown");
     e.keyCode = keyCode;
     e.which = e.keyCode;
     e.altKey = false;
     e.ctrlKey = true;
     e.shiftKey = false;
     e.metaKey = false;
     e.bubbles = true;
     document.dispatchEvent (e);
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jacob
  • 595
  • 1
  • 7
  • 25
  • Looks like a duplicate of https://stackoverflow.com/questions/10455626/keydown-simulation-in-chrome-fires-normally-but-not-the-correct-key – mplungjan Jun 26 '17 at 12:43
  • Possible duplicate of [Keydown Simulation in Chrome fires normally but not the correct key](https://stackoverflow.com/questions/10455626/keydown-simulation-in-chrome-fires-normally-but-not-the-correct-key) – Brian Tompsett - 汤莱恩 Sep 29 '19 at 12:05

1 Answers1

0
document.addEventListener ('keydown', function (event) { // pass the event 
 console.log (JSON.stringify (event.keyCode))
}, false);

You need to get access to the event so include the variable event within the function header

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Thomas
  • 2,431
  • 17
  • 22
  • _If I open the developer console I can see that the event is successfully dispatched_ - the window.event is available to many browsers without being specifically passed to the function – mplungjan Jun 26 '17 at 12:30
  • @mplungjan I'm able to print the event.keyCode. My problem is that the event that I dispatch doesn't write the letter in the input text field. I'm sending the keycode 89(letter W) and I want it to be written in a text input field. But it's not happening. – Jacob Jun 26 '17 at 12:35