This is a more specific question of Is it possible to simulate key press events programmatically? Every answer is missing the following information in one way or another, reducing the question's value. I've tried three things on there already that didn't work in modern browsers, or were advised against by official sources.
Here is what I'm looking for:
This solution fills all of the criteria:
key
equal to one of these values https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values (I would embed this, however, there are a lot of codes)ctrlKey
option (boolean) altKey
option (boolean) shiftKey
option (boolean) metaKey
option (boolean) function simulateKeypress(target, options) { target.dispatchEvent(new KeyboardEvent('keydown', options)); } document.addEventListener("keydown", event => { console.log(event.key); }); setTimeout(() => { simulateKeypress(document, { key: "F1" }); }, 1000);
(As already stated on the linked original question, it is unclear what "simulate" means here . However:)
We maintain a package for simulating user events for testing at @testing-library/user-event .
This includes userEvent.type()
API for conveniently simulating keyboard input to input elements as well as userEvent.keyboard()
API for simulating keyboard events anywhere. The library simulates the common browser behavior. It will dispatch the key events, change element values, move selection and focus - dependent on the pressed keys and possibly custom event handler that eg stop propagation.
The primary target audience for the library is testing with jest
and jsdom
, but other environments including testing in real browsers are also supported.
(For examples and further explanations see the linked docs. For missing features, bugs, etc.: Issues and PRs are always welcome at the linked Github repo :) )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.