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.


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.


IMHO you're going about this all wrong. Angular is not "listening" to keypress or the like. It is listening to change and input events. See the example below. It does (admittedly it is simple) what you need.

var iButton = document.getElementById('inputButton');
iButton.addEventListener('click', simulateInput);

var cButton = document.getElementById('changeButton');
cButton.addEventListener('click', simulateChange);

function simulateInput() {
  var inp = document.getElementById('name');
  var ev = new Event('input');
  
  inp.value =inp.value + 'a';
  inp.dispatchEvent(ev);
}

function simulateChange() {
  var inp = document.getElementById('name');
  var ev = new Event('change');
  
  inp.value = 'changed';
  inp.dispatchEvent(ev);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="">
 
<p>Input something in the input box:</p>
<p>Name : <input id="name" type="text" ng-model="name" placeholder="Enter name here"></p>
<h1>Hello {{name}}</h1>

</div>

<button id="inputButton">I simulate the "input" event.</button>
<button id="changeButton">I simulate the "change" event.</button>