Created
April 29, 2020 10:28
-
-
Save GlauberF/d8278ce3aa592389e6e3d4e758e6a0c2 to your computer and use it in GitHub Desktop.
A function for simulating key event in JavaScript. You just have to choose what key and keyboard event you want to simulate.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Simulate a key event. | |
* @param {Number} keyCode The keyCode of the key to simulate | |
* @param {String} type (optional) The type of event : down, up or press. The default is down | |
* @param {Object} modifiers (optional) An object which contains modifiers keys { ctrlKey: true, altKey: false, ...} | |
*/ | |
function simulateKey (keyCode, type, modifiers) { | |
var evtName = (typeof(type) === "string") ? "key" + type : "keydown"; | |
var modifier = (typeof(modifiers) === "object") ? modifier : {}; | |
var event = document.createEvent("HTMLEvents"); | |
event.initEvent(evtName, true, false); | |
event.keyCode = keyCode; | |
for (var i in modifiers) { | |
event[i] = modifiers[i]; | |
} | |
document.dispatchEvent(event); | |
} | |
// Setup some tests | |
var onKeyEvent = function (event) { | |
var state = "pressed"; | |
if (event.type !== "keypress") { | |
state = event.type.replace("key", ""); | |
} | |
console.log("Key with keyCode " + event.keyCode + " is " + state); | |
}; | |
document.addEventListener("keypress", onKeyEvent, false); | |
document.addEventListener("keydown", onKeyEvent, false); | |
document.addEventListener("keyup", onKeyEvent, false); | |
// Using the function | |
simulateKey(38); | |
simulateKey(38, "up"); | |
simulateKey(45, "press"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
some improvements and applied the function to typescript.
what to call
Tested on Chrome ( Version 110.0.5481.77 (Official Version) 64-bit)