Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript detecting play/pause keyboard (virtual) key

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.

like image 452
Joeytje50 Avatar asked Jun 12 '19 12:06

Joeytje50


2 Answers

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

like image 184
David Major Avatar answered Nov 16 '22 16:11

David Major


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+

like image 6
Jesse Reza Khorasanee Avatar answered Nov 16 '22 15:11

Jesse Reza Khorasanee