问题
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:
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.
来源:https://stackoverflow.com/questions/20163708/dispatching-keyboard-event-doesnt-work-in-javascript