javascript - Sending keyboard events programmatically doesn't dispatch them into inputs - Stack Overflow

I am sending programmatically generated keyboard events to the document. I was hoping that the currentl

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?

Share Improve this question asked Jul 31, 2017 at 9:51 Philip FeldmannPhilip Feldmann 8,4357 gold badges44 silver badges66 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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/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?)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742372318a4431500.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信