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!
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!
Share asked Jul 20, 2018 at 15:29 14jbella14jbella 5354 silver badges15 bronze badges 2- 2 stackoverflow./questions/3630191/… seems to only work on Windows – Luca Kiebel Commented Jul 20, 2018 at 15:32
- Google Play Music supports this. Works on my mac with Chrome and a Windows Media keyboard plugged in. – ficuscr Commented Jul 20, 2018 at 15:34
1 Answer
Reset to default 10The 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.