Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Chrome: Simulate keypress events on input text field using javascript

There is a lot of contents on this in stack overflow but none seems to work for my case. I have an input text field and I want to simulate keypress event to fill the text field.

Reason: I am automating a lot of data entry task on a web interface which provides no API. Changing the input field using .value does not trigger the JS side (angular) of the interface. That is why I want to simulate keypress event.

First I tried this:

var inp = document.getElementById('rule-type');
inp.dispatchEvent(new KeyboardEvent('keypress',{'key':'a'}));

Then I learned in Chrome the key and code stays as 0 and does not change in KeyBoardEvent.

So I created seperate event ev = new KeyboardEvent('keypress',{'key':'a', 'code': 'KeyA'})

And then I dispatched again, the return statement is true but it does not change the input field.

The solution needs to be in pure javascript not jQuery.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You will not be able to fire an event that will cause text to populate an input. See this snippet from MDN:

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.

Thanks @gforce301

Your best bet may be to set the value and then dispatch an event.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...