I am trying to simulate key event (press) on Chrome 53. All the solutions that I found on StackOverflow seems not to be working..
My goal is to have a function that gets a keyCode
and simulates a key press with it - Pure JS is required
function keyPressSimulate(keyCode) {...?}
Code samples that I already tried:
Node.prototype.fire=function(type,options){
var event=new CustomEvent(type);
for(var p in options){
event[p]=options[p];
}
this.dispatchEvent(event);
}
document.fire("keyup",{ctrlKey:true,keyCode:90,bubbles:true})
Another one:
presskey: function(k) {
var e = new Event("keydown");
e.keyCode= k;
e.which=e.keyCode;
e.altKey=false;
e.ctrlKey=true;
e.shiftKey=false;
e.metaKey=false;
document.dispatchEvent(e);
}
And:
var e = new KeyboardEvent("keydown", {bubbles : true, cancelable : true, key : "Q", shiftKey : true});
global.document.dispatchEvent(e);
And:
presskey: function(k) {
var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";
keyboardEvent[initMethod](
"keydown",
true, // bubbles oOooOOo0
true, // cancelable
window, // view
false, // ctrlKeyArg
false, // altKeyArg
false, // shiftKeyArg
false, // metaKeyArg
k,
0 // charCode
);
global.document.activeElement.dispatchEvent(keyboardEvent);
}