调度键盘事件在 JavaScript 中不起作用
我正在尝试使用 JavaScript 在浏览器中模拟用户输入.Click 事件已成功创建和分派,但由于某些原因,键盘事件的类似代码似乎根本不起作用.
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);
这会返回 true,但相应的字符不会出现在输入中.我也尝试过 keypress 和 keyup 也不起作用(针对 FF 和 Chrome 进行了测试).浏览器是否出于某些安全原因禁止它,或者我做错了什么?有没有办法让它工作?
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?
推荐答案
事件调度正常,所有事件监听器都会触发,没有发生的事情是角色没有被输入".这是因为事件的起源不是来自正确的来源.这是一个安全功能".
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.
相关文章