Access to "media keys" from within a browser tab

Viewed 10378

Is there a way to access the "media keys" with Javascript from within a browser tab/window?

I am mainly interested in a google chrome solution.

Using the following code, there doesn't seem to be an event generated for the media keys:

<html>
<body onKeyDown="showKeyCode(event)">
    <script type="text/javascript">

        function showKeyCode(event) {
            alert(event.keyCode);
        }

    </script>
</body>
</html>

Am I missing something? Could I do better with a Google Chrome extension??

Update: to address this problem I crafted the following tools:

4 Answers

As of Chrome 73, there's explicit support for media keys, see https://developers.google.com/web/updates/2019/02/chrome-73-media-updates

In summary, you can install an event handler with

navigator.mediaSession.setActionHandler('previoustrack', function() {
  // User hit "Previous Track" key.
});

The document above gives a good overview.

https://googlechrome.github.io/samples/media-session/ has example code and a demo.

https://developer.mozilla.org/en-US/docs/Web/API/Media_Session_API has more detailed documentation.

As it seems, there is now a possibility to execute JS code on media key presses. I took mikemaccana's answer and looked up the KeyEvent:

$(ready);

function ready() {
  $(document).on('keydown', onKeyDown);
}

function onKeyDown(ev) {
  if (ev.code === 'MediaPlayPause') alert('Play/Pause');
  if (ev.code === 'MediaStop') alert('Stop');
  if (ev.code === 'MediaTrackPrevious') alert('Previous Track');
  if (ev.code === 'MediaTrackNext') alert('Next Track');    
  if (ev.code === 'VolumeUp') alert('Volume Up');
  if (ev.code === 'VolumeDown') alert('Volume Down');
  if (ev.code === 'VolumeMute') alert('Volume Mute');
}

You can just do alert(ev.code); in onKeyDown to get the key codes.

I uploaded this example on JSFiddle so you can test it.

Related