0

I just ran into a problem. I wanted to write a small script that wrote into an input field by simulating key presses. But it doesn't work.

<input type="text" id="mainInput" />
const inputElement = document.getElementById("mainInput");

for (let i = 0; i < 100; i++) {

  const newEvent = new KeyboardEvent("keypress", {
      charCode: 115,
      key: "s",
      which: 115
  });
  inputElement.dispatchEvent(newEvent);
}

I also attached an event listener and could confirm that my event is triggered correctly. I assume it is because the isTrusted flag is false and I understand that I cannot change that when I create an event via javascript.

But I skimmed now twice over the documetation of the input and text input field on MDN. In it has no mention of that. Because of that I cannot be sure if it really is the isTrusted flag or if I do something wrong. I am pretty convinced of it, but that's still different from having definite confirmation.

So, my question is two-fold: 1. Is it the isTrusted flag why it isn't working? 2. Where could I have read about it? Did I overlook it on MDN? Or is it hidden in some obscure RFC?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
TheCommoner282
  • 205
  • 1
  • 7
  • 1
    "*I could confirm that my event is triggered correctly.*" - then what does not work? – Bergi Nov 11 '19 at 23:03
  • The input field remains empty in spite the correctly fired event. – TheCommoner282 Nov 12 '19 at 01:58
  • I think firing the `keypress` event and adjusting the `.value` of the input are two separate things the browser does. – Bergi Nov 12 '19 at 02:27
  • Yeah, of course I could have adjusted the value. But that would not have fulfilled the goal condition, which was to simulate key input. I suppose it is how the browser does it. But supposedly with the isTrusted flag – TheCommoner282 Nov 12 '19 at 20:09
  • 1
    No, I don't think it has anything to do with `isTrusted`. That's just a convenience for listeners. From https://googlechrome.github.io/samples/event-istrusted/: "*This property is intended primarily for use by browser extensions, to determine if an event was dispatched by a script running in the main world or not.*" – Bergi Nov 12 '19 at 20:35
  • Possible duplicate of [JavaScript trigger an InputEvent.isTrusted = true](https://stackoverflow.com/q/49518959/1048572). It's not the event that causes the `.value` to change. It's the user input that both triggers the event *and* changes the `.value`. – Bergi Nov 12 '19 at 20:37

0 Answers0