Search code examples
javascriptgoogle-chromemedia-playerdom-events

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.


Solution

  • 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+