Search code examples
javascriptkeypressevent-listener

Is it possible to use media keys to control a website?


I am building a website which includes an audio player. I suspect it is not possible, because I have not seen websites that do this, but is there any way to allow the user to control my player using the media keys (i.e. pause, play, stop, skip) on their keyboard?

Since I built the player all I need is to detect keypress or keydown events for these keys, and the rest should be simple.

Ideally, a cross-browser solution would be nice, but even if it only works in some browsers, it would be nice to add this functionality for browsers that support these keys.

Or, if this is a bad practice for any reason, please let me know!


Solution

  • The Media Session API lets you listen for media key events in the browser:

    navigator.mediaSession.setActionHandler('play', () => console.log('play'));
    navigator.mediaSession.setActionHandler('pause', () => console.log('pause'));
    navigator.mediaSession.setActionHandler('seekbackward', () => console.log('seekbackward'));
    navigator.mediaSession.setActionHandler('seekforward', () => console.log('seekforward'));
    navigator.mediaSession.setActionHandler('previoustrack', () => console.log('previoustrack'));
    navigator.mediaSession.setActionHandler('nexttrack', () => console.log('nexttrack'));
    

    It is supported by all modern browsers.