Skip to content

Instantly share code, notes, and snippets.

@ejoubaud
Last active April 9, 2024 18:38
Show Gist options
  • Save ejoubaud/7d7c57cda1c10a4fae8c to your computer and use it in GitHub Desktop.
Save ejoubaud/7d7c57cda1c10a4fae8c 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
@fqdeng
Copy link

fqdeng commented Apr 2, 2020

very good, I lost my two hours in simulating arrow key for the Chrome browser. Jquery simulation won't work, this scripts works.

@shudal
Copy link

shudal commented Apr 29, 2020

好活

@GautamBose
Copy link

Works great in chrome 81, thank you!

@lakpahana
Copy link

lakpahana commented May 27, 2021

Works great in chrome 91, thank you!
I tried on dev console.

@jaspreetsinghrawel
Copy link

jaspreetsinghrawel commented Jun 16, 2021

I wanted to simulate key "1" press.
so called Podium.keydown(49) on chrome 91. Did not work.
Even i tried enter key with code 13. it did not work. What could be wrong.
There is a webpage which does operations based on shortcut keys. So my requirement is to press "1".

@pouriazareie
Copy link

Did not work dude this wrong and i do
fix it

@codeyourwayup
Copy link

looks good, how to pass element to it, for example a button with class 'the-btn'? thanks

@anhtata
Copy link

anhtata commented Oct 16, 2023

Great! It's work! Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment