admin管理员组文章数量:1335624
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)
})
}
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?
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)
})
}
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?
1 Answer
Reset to default 8It 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/en/docs/Web/API/Event/isTrusted
I tried to solve this in here: https://codepen.io/zvona/pen/LjNEyr?editors=1010
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?)
本文标签: javascriptSending keyboard events programmatically doesn39t dispatch them into inputsStack Overflow
版权声明:本文标题:javascript - Sending keyboard events programmatically doesn't dispatch them into inputs - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742372317a2462473.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论