admin管理员组文章数量:1277898
I'm trying to autoplay a video as soon as the user interacted with the page. If I play the video before, I obviously get a security error :
Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.
That's fair, I catch this error and now want to register an event to retry the play as soon as the user interacted with the page.
=> Is there such an event available ?
I tried to register events on mouseover / mousemove / touchmove / click / focus / visibilitychanged but it's not optimal, and not very reliable after some tests ...
I'm trying to autoplay a video as soon as the user interacted with the page. If I play the video before, I obviously get a security error :
Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.
That's fair, I catch this error and now want to register an event to retry the play as soon as the user interacted with the page.
=> Is there such an event available ?
I tried to register events on mouseover / mousemove / touchmove / click / focus / visibilitychanged but it's not optimal, and not very reliable after some tests ...
Share Improve this question asked Sep 4, 2018 at 10:06 JsctiJscti 14.5k5 gold badges65 silver badges89 bronze badges2 Answers
Reset to default 8I know this is an old question, but for anyone working with this issue, play()
returns a promise. So you could do something similar to the below code. This code would attempt to fire the play()
function every 5 seconds until it successfully is able to, then it will clear the interval.
Not sure if it applies to video as well but I would assume so.
const tryToPlay = setInterval(() => {
const audio = new Audio(theAudioFile);
audio.play()
.then(() => {
clearInterval(tryToPlay);
})
.catch(error => {
console.info('User has not interacted with document yet.');
});
}, 5000);
Register multiple events and wait for one to work.
let isPlaying = false;
["click", "mousemove", "mouseover", "mousemove", "touchmove", "focus"].forEach((eventName)=>{
window.addEventListener(eventName, ()=>{
if(!isPlaying){
try{
//play video here
console.log("Video is playing");
isPlaying = true;
}catch(e){
console.warn(e.message);
}
}
});
});
本文标签: javascriptIs there an event to detect when user interacted with a pageStack Overflow
版权声明:本文标题:javascript - Is there an event to detect when user interacted with a page? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741243064a2364355.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论