Sending keyboard events programmatically doesn't dispatch them into inputs

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-02 10:16:16

问题


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:


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;
});

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



来源:https://stackoverflow.com/questions/45412590/sending-keyboard-events-programmatically-doesnt-dispatch-them-into-inputs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!