問題描述
我正在嘗試使用 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.
這篇關于調度鍵盤事件在 JavaScript 中不起作用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!