Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

javascript - 使用dispatchEvent以编程方式发送键以进行输入(Programmatically send keys to input using dispatchEvent)

I'm trying to send characters to an input element based on user actions.

(我正在尝试根据用户操作将字符发送到输入元素。)

I'm trying to use KeyboardEvent with dispatchEvent but whatever I do, it doesn't work

(我正在尝试将KeyboardEventdispatchEvent一起使用,但是无论我做什么,它都无法正常工作)

For example:

(例如:)

let keyEvent = new KeyboardEvent();
keyEvent.key = 'a';
keyEvent.keyCode = 'a'.charCodeAt(0);
keyEvent.which = event['keyCode'];
keyEvent.altKey = false;
keyEvent.ctrlKey = true;
keyEvent.shiftKey = false;
keyEvent.metaKey = false;
keyEvent.bubbles = true;

Not sure if this is correct, but I have dispatched it as follows:

(不知道这是否正确,但是我已按如下方式调度它:)

  document.querySelector('input').dispatchEvent(keyEvent);
  document.activeElement.dispatchEvent(keyEvent);
  document.dispatchEvent(keyEvent);

DEMO

(演示)

If I first focus the input before clicking the button nothing really happens.

(如果我在单击按钮之前先关注输入内容,则什么也没有发生。)

Any suggestions what might go wrong here ?

(有什么建议可能会出什么问题吗?)

  ask by Jeanluca Scaljeri translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Actually, due to security reasons, dispatching a KeyboardEvent to an input element does not generate the action you expect.

(事实上,由于安全原因,分派KeyboardEventinput元素没有产生预期的作用。)

The KeyboardEvent document makes it quite clear:

(KeyboardEvent文档非常清楚:)

Note: manually firing an event does not generate the default action associated with that event.

(注意:手动触发事件不会生成与该事件关联的默认操作。)

For example, manually firing a key event does not cause that letter to appear in a focused text input.

(例如,手动触发按键事件不会导致该字母出现在焦点文本输入中。)

In the case of UI events, this is important for security reasons, as it prevents scripts from simulating user actions that interact with the browser itself.

(对于UI事件,出于安全原因,这很重要,因为它可以防止脚本模拟与浏览器本身交互的用户操作。)

So the dispatchEvent stuff simply won't work.

(所以dispatchEvent东西根本就行不通。)

Alternatively, consider manipulating the input element directly.

(或者,考虑直接操作input元素。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...