使用JavaScript禁用媒体控制键 [英] Disable media control keys with javascript
问题描述
我正在使用javascript(没有jQuery)在网站上构建类似键盘的应用程序,但是每次单击图像时,声音文件都会播放/暂停,而不是播放一个音符.我已经设法使其正常运行,但是还有一件事困扰着我.也就是说,在使用Chrome时,通过使用键盘上的媒体控件,仍可以播放和/或暂停音频文件之一.我不打算自定义或学习此功能,我只想为我的网站禁用它.这可能吗?
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?
推荐答案
Media Session API 可让您监听媒体键事件并在所述事件上执行任意代码:
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() {});
这篇关于使用JavaScript禁用媒体控制键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!