Dispatching keyboard event doesn't work in JavaScript
Asked Answered
E

1

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?

Epiclesis answered 23/11, 2013 at 14:44 Comment(1)
did you solve it?Armes
B
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.

Beggarly answered 23/11, 2013 at 15:7 Comment(1)
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?Epiclesis

© 2022 - 2024 — McMap. All rights reserved.