Created
November 1, 2019 19:47
-
-
Save paitonic/c83ae83f275a7be87a017b74bc13d05f to your computer and use it in GitHub Desktop.
simulateKeyPress
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
| function keyboardEventFromText(text) { | |
| return [...text].flatMap((letter) => { | |
| return [ | |
| new KeyboardEvent('keydown', {key: letter}), | |
| new KeyboardEvent('keypress', {key: letter}), | |
| new InputEvent('input', {data: letter, inputType: 'insertText'}), | |
| new KeyboardEvent('keyup', {key: letter}), | |
| ] | |
| }) | |
| } | |
| function simulateKeyPress(element, text) { | |
| element.value = text; | |
| const events = [ | |
| new FocusEvent('focus'), | |
| new FocusEvent('focusin'), | |
| new MouseEvent('click'), | |
| // ...keyboardEventFromText(text), | |
| new Event('change'), | |
| ].forEach((event) => { | |
| element.dispatchEvent(event); | |
| }) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment