Skip to content

Instantly share code, notes, and snippets.

@probablycorey
Last active December 20, 2015 06:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save probablycorey/6083039 to your computer and use it in GitHub Desktop.
Save probablycorey/6083039 to your computer and use it in GitHub Desktop.
Simulate keydown,keypress,keyup and textinput in chrome
# Shift still doesn't work
window.keydown = (key, {ctrl, shift, alt, meta}) ->
dispatchKeyboardEvent = (target, eventArgs...) ->
e = document.createEvent("KeyboardEvent")
e.initKeyboardEvent eventArgs...
target.dispatchEvent e
dispatchTextEvent = (target, eventArgs...) ->
e = document.createEvent("TextEvent")
e.initTextEvent eventArgs...
target.dispatchEvent e
element = document.activeElement
eventArgs = [true, true, null, key, 0, ctrl, alt, shift, meta] # bubbles, cancelable, view, key, location
console.log eventArgs
canceled = not dispatchKeyboardEvent(element, "keydown", eventArgs...)
dispatchKeyboardEvent(element, "keypress", eventArgs...)
if not canceled
if dispatchTextEvent(element, "textInput", eventArgs...)
element.value += key
dispatchKeyboardEvent(element, "keyup", eventArgs...)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment