samedi 27 février 2021

Simulating keyboard events with JavaScript

How to simulate typing of some text in a contenteditable element? I need to simulate everything as a user will events will do for test purposes. I can fire an event with:

node.dispatchEvent(new KeyboardEvent('keydown', {key: 'A'}))
node.dispatchEvent(new KeyboardEvent('keyup', {key: 'A'}))

But it will not print A. So I have to use API:

node.innerHTML += 'A'

But the cursor will be in a different place, so I need to create a range.

let r = document.createRange()
r.selectNodeContents(editor)
r.collapse(false)
let s = window.getSelection()!
s.removeAllRanges()
s.addRange(r)

What about simulating arrows? How to simulate arrow up? Maybe there is some library to do this?

Aucun commentaire:

Enregistrer un commentaire