Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 810
14jbella Avatar asked Nov 15 '25 19:11

14jbella


1 Answers

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.

like image 168
Ned Howley Avatar answered Nov 18 '25 09:11

Ned Howley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!