Automate string input to a input

Viewed 41

I know this question has been asked a hundred times. But once again, the solutions no longer work.

I need to simulate key presses to automate a form.

If I do it like this

document.getElementById("input_id").value = "testinput"

the events from the input do not trigger. And my value is just deleted again.

is there again a possibility to simulate keystrokes so that also all events are triggered?

2 Answers

You can dispatch keyboard events on an EventTarget (element, Window, Document, others) like this:

element.dispatchEvent(new KeyboardEvent('keydown', {'key': 'a'}));

Example:

let element = document.querySelector('input');
element.onkeydown = e => alert(e.key);
changeValButton.onclick = () => element.value += "a";
dispatchButton.onclick = () => {
  element.dispatchEvent(new KeyboardEvent('keydown',{'key':'E'}));
  element.dispatchEvent(new KeyboardEvent('keyup',{'key':'E'}));
}
<input type="text" value="">
<button id="dispatchButton">Press to dispatch event </button>
<button id="changeValButton">Press to change value </button>

I have now found the following code that works for me:

function set_value(doc, input_value) {
  doc.value === undefined ? doc.innerHTML = input_value : doc.value = input_value;
  events = ["keydown", "keypress", "input", "keyup", "change"]
  for (var i = 0; i < events.length; ++i) doc.dispatchEvent(new Event(events[i], {
    bubbles: true
  }));
}
Related