以编程方式发送键盘事件不会将它们分派到输入中

Phi*_*ann 3 javascript input keyboard-events

我将以编程方式生成的键盘事件发送到文档。我希望当前聚焦的输入元素能够显示它们,但事实并非如此。事件是使用以下函数从字符串生成的:

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)
  })
}
Run Code Online (Sandbox Code Playgroud)

如果我将 EventListener 添加到文档中,它将接收所有事件。然而,他们的isTrusted标志设置为 false,这可能是问题所在吗?

zvo*_*ona 8

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

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;
});
Run Code Online (Sandbox Code Playgroud)

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?)