Skip to content

Instantly share code, notes, and snippets.

@paitonic
Created November 1, 2019 19:47
Show Gist options
  • Select an option

  • Save paitonic/c83ae83f275a7be87a017b74bc13d05f to your computer and use it in GitHub Desktop.

Select an option

Save paitonic/c83ae83f275a7be87a017b74bc13d05f to your computer and use it in GitHub Desktop.
simulateKeyPress
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