JavaScript detecting play/pause keyboard (virtual) key

余生颓废 提交于 2020-12-03 15:50:05

问题


By accident, I just pressed the play/pause (▶/❚❚) button on my keyboard (the button just above Num Lock on , 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.


回答1:


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




回答2:


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+. I'll update this awnser if I find a Firefox equivelent.



来源:https://stackoverflow.com/questions/56562501/javascript-detecting-play-pause-keyboard-virtual-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!