[英]How to simulate keyboard press “full stack” with JS?
I've read and tried the solutions for this question but none of them work as I expect.我已经阅读并尝试了这个问题的解决方案,但它们都没有像我预期的那样工作。
In the code snippet below I register two event listeners and see both callbacks fire as a response to the keydown
event on the input
and document
.在下面的代码片段中,我注册了两个事件侦听器,并看到两个回调都作为对
input
和document
上的keydown
事件的响应而触发。
However, my expectation is that when this line of code runs there's an additional text entered into the input, a
.但是,我的期望是,当这行代码运行时,会在输入中输入一个额外的文本,
a
.
input.dispatchEvent(keyEvent);
In other words, I expect that invoking dispatchEvent
on the input
element with KeyboardEvent
as an argument should add text to the input, however it does not .换句话说,我希望使用
KeyboardEvent
作为参数在input
元素上调用dispatchEvent
应该将文本添加到输入中,但它不会。
It does invoke the callbacks registered with the eventListener.它确实调用了在 eventListener 中注册的回调。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input id="input">
<script>
const input = document.getElementById('input')
input.addEventListener('keydown', (e) => {
console.log('Keydown on Input: ', e.key)
})
document.addEventListener('keydown', (e) => {
console.log('Keydown on Doc: ', e.key)
})
function focusInputThenFireEventKeyboardEvents() {
input.value = 'I want '
input.focus()
input.dispatchEvent(new Event('focus'));
input.dispatchEvent(new KeyboardEvent('keypress',{'key':'a'}));
input.dispatchEvent(new KeyboardEvent('keydown',{'key':'a'}));
var keyEvent = new KeyboardEvent("keydown", { key: "a", char: "a", shiftKey: true });
var keyEvent2 = new KeyboardEvent("keydown", { key: "d", char: "d", shiftKey: true });
input.dispatchEvent(keyEvent);
document.dispatchEvent(keyEvent2);
}
setTimeout(focusInputThenFireEventKeyboardEvents, 500)
</script>
</body>
</html>
You can check documentation here - https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent which says that keyboard event indicates user's interaction with key on keyboard and in order to handle text input you need to use input event.您可以在此处查看文档 - https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent表示键盘事件表示用户与键盘上的键的交互,并且为了处理您需要使用的文本输入输入事件。 Even if you dispatch an event like const input.dispatchEvent(new Event("input", {"bubbles":true, "cancelable":false})) it doesn't mean it will change the input but you can use it to programmatically set the value of input.
即使您调度像 const input.dispatchEvent(new Event("input", {"bubbles":true, "cancelable":false})) 这样的事件,这并不意味着它会更改输入,但您可以使用它来以编程方式设置输入的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.