I'm trying to simulate a keyboard event in Safari using JavaScript.
I have tried this:
var event = document.createEvent("KeyboardEvent"); event.initKeyboardEvent("keypress", true, true, null, false, false, false, false, 115, 0);
...and also this:
var event = document.createEvent("UIEvents"); event.initUIEvent("keypress", true, true, window, 1); event.keyCode = 115;
After trying both approaches, however, I have the same problem: after the code has been executed, the keyCode
/which
properties of the event object are set to 0
, not 115
.
Does anyone know how to reliably create and dispatch a keyboard event in Safari? (I'd prefer to achieve it in plain JavaScript if possible.)
There are three different keyboard events in JavaScript: keydown : Keydown happens when the key is pressed down, and auto repeats if the key is pressed down for long. keypress : This event is fired when an alphabetic, numeric, or punctuation key is pressed down. keyup : Keyup happens when the key is released.
keydown: This event is triggered when a key is pressed down. keypress: This event is triggered when a key is pressed. This event fails to recognise keys such as tab, shift, ctrl, backspace etc. keyup: This event is triggered when a key is released.
keydown – fires when you press a key on the keyboard and it fires repeatedly while you holding down the key.
I am working on DOM Keyboard Event Level 3 polyfill . In latest browsers or with this polyfill you can do something like this:
element.addEventListener("keydown", function(e){ console.log(e.key, e.char, e.keyCode) }) var e = new KeyboardEvent("keydown", {bubbles : true, cancelable : true, key : "Q", char : "Q", shiftKey : true}); element.dispatchEvent(e); //If you need legacy property "keyCode" // Note: In some browsers you can't overwrite "keyCode" property. (At least in Safari) delete e.keyCode; Object.defineProperty(e, "keyCode", {"value" : 666})
UPDATE:
Now my polyfill supports legacy properties "keyCode", "charCode" and "which"
var e = new KeyboardEvent("keydown", { bubbles : true, cancelable : true, char : "Q", key : "q", shiftKey : true, keyCode : 81 });
Examples here
Additionally here is cross-browser initKeyboardEvent separately from my polyfill: (gist)
Polyfill demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With