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

Sending keyboard events programmatically doesn't dispatch them into inputs

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

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 但是,这可能是问题所在吗?

无法通过网站以编程方式完成。就像你说的 isTrusted boolean as false 不会正确触发按键(因为 Chrome 53):https://developer.mozilla.org/en/docs/Web/API/Event/isTrusted

我试图在这里解决这个问题:https://codepen.io/zvona/pen/LjNEyr?editors=1010

实际上唯一的区别是为 activeElement 分派事件,例如:document.activeElement.dispatchEvent(e);。此外,如果您能够挂钩输入的事件,则可以添加事件侦听器来完成这项工作:

input.addEventListener('keypress', (evt) => {
  evt.target.value += evt.key;
});

但如前所述,这不是可信事件。但是,这可以通过浏览器扩展来完成(参见:How to to initialize keyboard event with given char/keycode in a Chrome extension?