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?