Skip to content

Instantly share code, notes, and snippets.

@ironfroggy
Forked from ejoubaud/simulate_keypress.js
Created May 16, 2023 15:15
Show Gist options
  • Save ironfroggy/1785b5fcca64a0b05f5ea51eafec7345 to your computer and use it in GitHub Desktop.
Save ironfroggy/1785b5fcca64a0b05f5ea51eafec7345 to your computer and use it in GitHub Desktop.
Simulate keypress that works in Google nav in Chrome
// Based on http://stackoverflow.com/a/10520017/1307721 and http://stackoverflow.com/a/16022728/1307721
Podium = {};
Podium.keydown = function(k) {
var 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, k, k, "", "", false, "");
} else {
oEvent.initKeyEvent("keydown", true, true, document.defaultView, false, false, false, false, k, 0);
}
oEvent.keyCodeVal = k;
if (oEvent.keyCode !== k) {
alert("keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")");
}
document.body.dispatchEvent(oEvent);
}
Podium.keydown(40); // for arrow-down, arrow-up is 38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment