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.)
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