Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating keyboard press in a way that isn't deprecated?

I am looking for a way to simulate a keyboard press (like the titled suggests). I have looked around and I have found mainly these 2 SO questions:

  • Is it possible to simulate key press events programmatically?
  • Simulate keypress without jquery

The issue with those are that they both use the KeyboardEvent.initKeyboardEvent() event which according to MDN it is deprecated. Is there a different way of accomplishing the same thing without that deprecated function?

I would like to know this because I am creating a script for YouTube using Chrome's TamperMonkey extension. This script will, when [space] is pressed, trigger K. K is YouTube's toggle play/pause button. I have the [space] listener working perfectly with the code below:

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

Also I am really looking for a pure JavaScript approach.

like image 575
ZomoXYZ Avatar asked Feb 05 '16 15:02

ZomoXYZ


1 Answers

If you do this with jQuery you build your event.

https://stackoverflow.com/a/3368599/3257830

If you want to create an event, you initialize the object 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>
like image 140
Roger Avatar answered Sep 22 '22 10:09

Roger