Last active
April 9, 2024 19:00
-
-
Save ejoubaud/a6667323763eeeadaa38a26ec051cb1d to your computer and use it in GitHub Desktop.
Trigger keyboard event in Javascript, works in OSX Chrome 58
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
// Based on http://stackoverflow.com/a/10520017/1307721 | |
// which wouldn't work for my use-case on my Mac because metaKey would always be true, for some reason | |
// Adapted to override metaKey to false | |
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; | |
} | |
}); | |
var metaKey = false; | |
Object.defineProperty(oEvent, 'metaKey', { | |
get : function() { | |
return metaKey; | |
} | |
}); | |
if (oEvent.initKeyboardEvent) { | |
oEvent.initKeyboardEvent("keydown", true, true, document.defaultView, false, false, false, false, k, k); | |
} 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) => arrowdown ; Podium.keydown(38) => arrowup |
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
var keyCode = 40; | |
var e = document.createEvent('KeyboardEvent'); | |
Object.defineProperty(e, 'keyCode', { get: function() { return keyCode; } }); | |
Object.defineProperty(e, 'which', { get : function() { return keyCode; } }); | |
Object.defineProperty(e, 'metaKey', { get : function() { return false; } }); | |
e.initKeyboardEvent("keydown", true, true, document.defaultView, false, false, false, false, keyCode, keyCode); | |
e.keyCodeVal = keyCode; | |
if (e.keyCode !== keyCode) { alert("keyCode mismatch " + e.keyCode + "(" + e.which + ")"); } | |
document.body.dispatchEvent(e); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment