Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable media control keys with javascript

I'm building a keyboard-like application on a website using javascript (no jQuery), but instead of one note being played a sound file plays/pauses every time you click on an image. I've managed to get it working, but there's still one thing bugging me. That is that one can still play and/or pause one of the audio files by using the media controls on their keyboard when using Chrome. I'm not looking into customizing or learning about this feature, I would just like to disable it for my site. Is this possible?

like image 437
NorthLake Avatar asked Oct 21 '25 08:10

NorthLake


1 Answers

The Media Session API lets you listen for media key events and execute arbitrary code on said events:

navigator.mediaSession.setActionHandler('play', function() { /* Code excerpted. */ });
navigator.mediaSession.setActionHandler('pause', function() { /* Code excerpted. */ });
navigator.mediaSession.setActionHandler('seekbackward', function() { /* Code excerpted. */ });
navigator.mediaSession.setActionHandler('seekforward', function() { /* Code excerpted. */ });
navigator.mediaSession.setActionHandler('previoustrack', function() { /* Code excerpted. */ });
navigator.mediaSession.setActionHandler('nexttrack', function() { /* Code excerpted. */ });

To prevent media key controls from fiddling with your elements leave the code block empty as such:

navigator.mediaSession.setActionHandler('play', function() {});
like image 177
N M Avatar answered Oct 23 '25 21:10

N M



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!