JavaScript Error: Uncaught (in promise) DOMException

问题: i am working on a web application that will play a song from JS. The code that I have is: const song = { play: () => { document.querySelector('body .audio...

问题:

i am working on a web application that will play a song from JS. The code that I have is:

const song =  {
    play: () => {
        document.querySelector('body .audio').play();
    },
    pause: () => {
        document.querySelector('body .audio').pause();
    }
};

When i call song.play(), I get an error in the console:

Uncaught (in promise) DOMException

No more, just that. I have tried to search the internet but nothing can give me the answer. How can I solve this problem.

Update: I have done some more research, and it turns out that i can call the exact same script from the console and it works, but not from a script.


回答1:

Autoplay Policy Changes

var promise = document.querySelector('audio').play();

if (promise !== undefined) {
  promise.then(_ => {
    // Autoplay started!
  }).catch(error => {
    // Autoplay was prevented.
    // Show a "Play" button so that user can start playback.
  });
}
  • 发表于 2019-01-08 00:35
  • 阅读 ( 1176 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除