10

By accident, I just pressed the play/pause (▶/❚❚) button on my keyboard (the button just above Num Lock on Lenovo keyboard, while playing a YouTube video in a tab that was not focused. To my massive surprise, the YouTube video paused immediately.

Now, I tried looking up how this works, but I was not able to find anything on the internet explaining how a keypress can be detected for keys like this. I tried running onkeydown = function(e) {console.log(e)} in my console, but pressing the play/pause button did not trigger any event. Also, https://keycode.info/ did not give me any help with this either. I did find http://www.kbdedit.com/manual/low_level_vk_list.html which lists a whole lot of 'virtual key codes', which does include VK_MEDIA_PLAY_PAUSE, which is probably the key I am pressing, but I did not find any way to trigger an event in JS with this.

Now I do want to specify that this functionality does not seem to work in Firefox, only in Chrome (as far as I've tested). It might be something that's still experimental, but I am really interested to hear what system YouTube uses to capture this event, even when the tab is currently not opened (Chrome wasn't even focused at the moment)

PS: I experienced this on Ubuntu 18.04; I'm not sure if this will work on Windows, for example.

Joeytje50
  • 18,636
  • 15
  • 63
  • 95

2 Answers2

6

Chrome is responsible for that (Hardware Media Key Handling), for more details check out chrome://flags/#hardware-media-key-handling

Also here is link that contains docs and demo: https://www.chromestatus.com/feature/5639924124483584

  • Is there any online resource that gives me a starting point to figure out how to use this? – Joeytje50 Jun 12 '19 at 13:08
  • 1
    Yea, i found this: https://www.chromestatus.com/feature/5639924124483584 You have some links to docs there, but i'm still not sure what is your overall goal. – David Major Jun 13 '19 at 11:48
  • 1
    Thanks, that looks like it has a clear demo, I can work with that. I am just looking to see if I can build similar functionality to the one in YouTube. Could you edit your answer to include that link, so that I can mark it as accepted? – Joeytje50 Jun 13 '19 at 12:21
  • Sure, it's done. Yea you can definitely build a similar functionality with this. :) – David Major Jun 13 '19 at 12:40
6

From Google Chrome Media Session Samples:

/* Media navigation Action handlers */

    navigator.mediaSession.setActionHandler('previoustrack', function() {
      console.log('> User clicked "Next Track" icon.');
    });

    navigator.mediaSession.setActionHandler('nexttrack', function() {
      console.log('> User clicked "Next Track" icon.');
    });

    navigator.mediaSession.setActionHandler('play', function() {
      log('> User clicked "Play" icon.');
      // Do something more than just playing audio...
    });

These chrome apis are availble on chrome 57+, and Firefox 82+

Jesse Reza Khorasanee
  • 3,140
  • 4
  • 36
  • 53