简体   繁体   中英

How can I emulate a keyboard press in a browser window with vanilla JavaScript?

I know similar questions to this have been asked before, but all of the answers I could find are either in jQuery or don't seem to work anymore. I've tried doing variations of

function send(char, elem) {
   let e = new KeyboardEvent('keydown', {key: char});
   elem.dispatchEvent(e);
}

but no luck. The event it dispatched and triggers the appropriate handlers, but the key is not typed if an input/textarea element is focused.

You can't make the typing occur from an event you trigger via the code - you can set up a listener, however, and make a custom event as so not to confuse the triggered event with a regular keypress.

 $("#button").on("click", function() { $("#input").trigger({ type: "myKeypress", which: "A".charCodeAt(0) }); }); $("#input").on("myKeypress", function(e) { $(this).val($(this).val() + String.fromCharCode(e.which)); }); 
 <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <input type="text" id="input"> <button id="button">Type A</button> 

You can make this work with all keys too:

 $("#button").on("click", function() { $("#input").trigger({ type: "myKeypress", which: prompt("Enter a letter").charCodeAt(0) }); }); $("#input").on("myKeypress", function(e) { $(this).val($(this).val() + String.fromCharCode(e.which)); }); 
 <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <input type="text" id="input"> <button id="button">Type a letter</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM