Created
January 13, 2022 11:06
-
-
Save crashmax-dev/f82c57a02ba0b681bd04e82506308a54 to your computer and use it in GitHub Desktop.
simulate KeyboardEvent
This file contains hidden or 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>KeyboardEvent</title> | |
<meta charset="UTF-8" /> | |
<script> | |
document.addEventListener("keydown", function (evt) { | |
if (evt.keyCode === 65 && evt.shiftKey) { | |
alert("SHIFT + A pressed"); | |
} | |
if (evt.keyCode === 75 && evt.ctrlKey) { | |
alert("CTRL + K pressed") | |
} | |
}); | |
function ctrl_k_hack() { | |
Podium = {}; | |
Podium.keydown = function (k) { | |
const oEvent = document.createEvent("KeyboardEvent"); | |
// Chromium Hack | |
Object.defineProperty(oEvent, "keyCode", { | |
get: function () { | |
return this.keyCodeVal; | |
} | |
}); | |
Object.defineProperty(oEvent, "which", { | |
get: function () { | |
return this.keyCodeVal; | |
} | |
}); | |
if (oEvent.initKeyboardEvent) { | |
oEvent.initKeyboardEvent( | |
"keydown", | |
true, | |
true, | |
document.defaultView, | |
false, | |
false, | |
true, | |
false, | |
k, | |
k | |
); | |
} else { | |
oEvent.initKeyEvent( | |
"keydown", | |
true, | |
true, | |
document.defaultView, | |
false, | |
false, | |
true, | |
false, | |
k, | |
0 | |
); | |
} | |
oEvent.keyCodeVal = k; | |
if (oEvent.keyCode !== k) { | |
alert( | |
"keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")" | |
); | |
} | |
document.dispatchEvent(oEvent); | |
}; | |
Podium.keydown(75); | |
} | |
function shift_a_good() { | |
const evt = new KeyboardEvent("keydown", { | |
shiftKey: true, | |
key: "A", | |
keyCode: 65 | |
}); | |
document.dispatchEvent(evt); | |
} | |
function ctrl_k_good() { | |
const evt = new KeyboardEvent("keydown", { | |
ctrlKey: true, | |
key: "K", | |
keyCode: 75 | |
}); | |
document.dispatchEvent(evt); | |
} | |
</script> | |
</head> | |
<body> | |
<p> | |
<button onclick="shift_a_good()">simulate good shift + a</button> | |
<button onclick="ctrl_k_good()">simulate good ctrl + k</button> | |
<button onclick="ctrl_k_hack()">simulate hack ctrl + k</button> | |
</p> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment