最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to use media keys to control a website? - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 10

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.

发布评论

评论列表(0)

  1. 暂无评论