Simulate a keystroke so that it is not obsolete?

I am looking for a way to simulate a keystroke on a keyboard (e.g. hints). I looked around and I basically found these two questions:

The problem is that they both use the KeyboardEvent.initKeyboardEvent() event, which is deprecated according to MDN . Is there any other way to accomplish the same thing without this deprecated function?

I would like to know this because I am creating a script for YouTube using the Chrome TamperMonkey extension. This script will, when [space] is pressed, call K. K - YouTube / Play / Pause button. I have a [space] listener that works fine with the code below:

 document.addEventListener("keydown", function(e) { if(e.keyCode==32) { e.preventDefault(); } }, false); 

Also I'm really looking for an approach using pure JavaScript.

+5
source share
1 answer

If you do this using jQuery, you will create your event.

fooobar.com/questions/47890 / ...

If you want to create an event, you initialize the object and then dispatch the event.

https://developer.mozilla.org/en-US/docs/Web/API/Event/Event

 document.addEventListener("keypress", function(e) { alert(e.which); }); var e = new Event("keypress"); e.which = 65; e.keyCode = 65; document.dispatchEvent(e); 
 <p id="r">Alerts on event</p> 
+1
source

Source: https://habr.com/ru/post/1242381/


All Articles