问题描述
我正在以编程方式将键盘事件发送到文档.我希望当前关注的输入元素能够显示它们,但是不会显示.这些事件是使用以下函数从字符串生成的:
I am sending programmatically generated keyboard events to the document. I was hoping that the currently focused input element would display them, however it doesn't. The events are generated from a string with this function:
const simulateKeyPress = keys => {
keys.split('').forEach(theKey => {
const e = new window.KeyboardEvent('keypress', {
bubbles: true,
key: theKey,
keyCode: theKey.charCodeAt(0),
charCode: theKey.charCodeAt(0),
})
document.dispatchEvent(e)
})
}
如果我将EventListener添加到文档中,它将接收所有事件.他们的isTrusted
标志设置为false,但这可能是问题所在吗?
If I add an EventListener to the document it'll receive all the events. Their isTrusted
flag is set to false however, might this be the issue?
推荐答案
无法从网站以编程方式完成.就像您说的那样,isTrusted
布尔值为false不会正确触发按键(因为Chrome 53): https://developer.mozilla.org/en/docs/Web/API/Event/isTrusted
It cannot be done from website programmatically. Like you said isTrusted
boolean as false will not trigger the keypress correctly (since Chrome 53): https://developer.mozilla.org/en/docs/Web/API/Event/isTrusted
我试图在此处解决此问题: https://codepen.io/zvona /pen/LjNEyr?editors = 1010
I tried to solve this in here: https://codepen.io/zvona/pen/LjNEyr?editors=1010
实际上,唯一的区别是为activeElement
调度事件,例如:document.activeElement.dispatchEvent(e);
.另外,如果您能够钩住输入的事件,则可以添加事件侦听器来完成此工作:
where practically only difference is to dispatch the event for activeElement
, like: document.activeElement.dispatchEvent(e);
. In addition, if you're able to hook on input's events, you can add event listener to do the job:
input.addEventListener('keypress', (evt) => {
evt.target.value += evt.key;
});
但是就像提到的那样,这不是可信任的事件.但是,这可以通过浏览器扩展来完成(请参阅:)
But like mentioned, it's not trusted event. However, this can be done via browser extensions (see: How to to initialize keyboard event with given char/keycode in a Chrome extension?)
这篇关于以编程方式发送键盘事件不会将它们分派到输入中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!