[英]How do I simulate a cross browser key press that works for alphanumeric and non-printable characters in JavaScript?
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)key
设置为等于这些值之一https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values (我会嵌入这个,但是,有很多代码)ctrlKey
option (boolean) ctrlKey
选项(布尔值)altKey
option (boolean) altKey
选项(布尔值)shiftKey
option (boolean) shiftKey
选项(布尔值)metaKey
option (boolean) metaKey
选项(布尔) 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 .我们在@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.这包括
userEvent.type()
API为方便模拟键盘输入到输入元素以及userEvent.keyboard()
API任何地方模拟键盘事件。 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.该库的主要目标受众是使用
jest
和jsdom
进行测试,但也支持其他环境,包括在真实浏览器中进行测试。
(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 :) ) (有关示例和进一步解释,请参阅链接的文档。对于缺少的功能、错误等:在链接的 Github 存储库中始终欢迎问题和 PR :))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.