Dispatching keyboard event doesn't work in JavaScript

蹲街弑〆低调 提交于 2020-01-04 05:22:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!