6

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:

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.

Community
  • 1
  • 1
ZomoXYZ
  • 1,763
  • 21
  • 44
  • 3
    Possibly useful. From MDN: "Web applications should use constructor instead of this if it's available." https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent – CollinD Feb 05 '16 at 15:24
  • 1
    Can you explain WHAT you are attempting? That will result in better answers – mplungjan Feb 05 '16 at 15:25
  • @mplungjan I am attempting to, when a user does a specific action (click a button or similar), this function will be triggered to make the page believe a specific key on the keyboard has been pressed. – ZomoXYZ Feb 05 '16 at 15:27
  • what is stopping you from executing the same callback on both types of events - user pressing a key or clicking on a button? – Aprillion Feb 05 '16 at 15:54
  • @Aprillion I made the question much more general. I am creating a script in a chrome extension that does not have direct access to the web page's code. I am making the script for YouTube to, when `[space]` is pressed, it will trigger `K`. `K` is YouTube's toggle play/pause button. I have the `[space]` listener working, but I cant seem to trigger `K`. I will edit my question to be a little more specific. – ZomoXYZ Feb 05 '16 at 16:00
  • 2
    Can you access youtube's API from your extension? (i.e. do you have access to `window.YT`?) If so, using that API directly would be a lot simpler than the roundabout approach of simulating keyboard events. – Daniel Beck Feb 05 '16 at 16:10
  • @CollinD I have just finished reading through that MDN page, and, unless I am mistaken, that function seems to only listen for the event, as the functions (different gecko and webkit) that initiate the event are both deprecated. – ZomoXYZ Feb 05 '16 at 16:10
  • @Jaketr00 Maybe I misunderstood, but it looks like you can use the optional second parameter to initialize an event. The docs aren't very clear on that though I agree. Maybe worth some testing. – CollinD Feb 05 '16 at 16:13
  • @DanielBeck It seems I do have access to that, what would be the correct way to toggle playback with that function? – ZomoXYZ Feb 05 '16 at 16:36
  • Get the individual player instance from `window.YT`, then call `.playVideo()` or `.pauseVideo()` on it. https://developers.google.com/youtube/iframe_api_reference – Daniel Beck Feb 05 '16 at 16:41
  • @DanielBeck I am not using an iframe, I am on the YouTube site. I have been trying to run `YT.Player.playVideo()`, but I get `YT is not defined`, then `yt.playVideo() is not a function`, and I have tried a bunch of variences like `yt.player.playVideo()` and `window.yt.player.playVide()` but nothing is working. But thanks for the article. – ZomoXYZ Feb 05 '16 at 16:49
  • 1
    I see, I assumed you were working with embeds, sorry. On the youtube site itself, `window.yt.player` exists (note lowercase), and has a `getPlayerByElement()` function; you may be able to use that to find the correct player object, though off the top of my head I'm not sure if the API will be usable there. – Daniel Beck Feb 05 '16 at 16:59
  • @DanielBeck I would like to add, I found this github project https://gist.github.com/VioletRed/d3678cdc700cd4d62fec and I read through it and found out that on the YT website you can use `window.document.getElementsByTagName('video')[0].pause()` and `window.document.getElementsByTagName('video')[0].play()` for HTML5 video. There is also a Flash fallback in the code. – ZomoXYZ Feb 05 '16 at 18:21

1 Answers1

2

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>
Community
  • 1
  • 1
Roger
  • 3,226
  • 1
  • 22
  • 38
  • 1
    Could someone explain why this was down-voted? I'm not defending the answer, just trying to learn. – ketchupisred Feb 05 '16 at 16:14
  • 2
    See the edit history. Downvotes are likely from when the answer was completely irrelevant to the question – Daniel Beck Feb 05 '16 at 16:18
  • This works great, except when I add `if (e.keyCode==65)` inside the keypress listener, this seems to not be triggered. I will test this in my script and see if it still works. EDIT: It does not seem to work, it just silently fails, and `event.preventDefault()` is supposed to stop the page from scrolling when `[space]` is pressed, but with the above script it does not prevent that anymore – ZomoXYZ Feb 05 '16 at 16:23
  • @Jaketr00 keyCode and which are 2 separate properties. If you want keyCode then add keyCode in your initialization as well. I edited my above answer to allow for keyCode to be checked as well. – Roger Feb 05 '16 at 16:25
  • Oh ok, that helps with my if statement. – ZomoXYZ Feb 05 '16 at 16:28