6

I'm trying to simulate user input in browser with JavaScript. Click events are created and dispatched successfully but for some reasons a similar code for keyboard events doesn't seem to work at all.

var event = document.createEvent("KeyboardEvent"); event.initKeyEvent("keydown", true, true, window, false, false, false, false, 87, 0); document.getElementById("id").dispatchEvent(event);

This returns true but the corresponding character doesn't appear in the input. I tried with keypress and keyup as well which don't work either (tested against FF and Chrome). Is it prohibited by browser for some security reasons or I'm doing something wrong? Is there a workaround to get it work?

1
  • did you solve it? Commented Jan 31, 2022 at 9:41

1 Answer 1

5

The event dispatches fine and all the event listeners will fire, the thing that does not happen is the character does not get "typed". This is because the origin of the event is not from the correct source. It's a "security feature".

The only way to simulate typing with resulting text is by re-setting the value or otherwise explicitly changing the contents of the node.

Sign up to request clarification or add additional context in comments.

1 Comment

You were right, "keypress" event handler is actually called too when I dispatch the event programmatically. What I don't get is why it is considered to be a security threat? I can always put some data into the value field of corresponding input and even submit a form with those data. Which issue does it solve?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.