You have to create a new KeyboardEvent . Initialize it and give it the property of the key you want to simulate.
The documentation of KeyboardEvent has never been very clear to me. Some recommend using key
and others using which
. Now I did the test and the following example does not send the charcode 32, but it does simulate pressing Space.
var event = new KeyboardEvent("keydown", {which:32, key:' ', code:'Space',keyCode:32, charCode:32});
document.dispatchEvent(event);
Apparently this is Chrome's own behavior because it works in Firefox. In Chrome I found the following (taken from an example in jsbin )
var eventObj = document.createEventObject ?
document.createEventObject() : document.createEvent("Events");
if(eventObj.initEvent){
eventObj.initEvent("keydown", true, true);
}
eventObj.keyCode = 32;
eventObj.which = 32;
eventObj.key=' ';
eventObj.code='Space';
document.dispatchEvent ? document.dispatchEvent(eventObj) : document.fireEvent("onkeydown", eventObj);