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

2 Answers 2

Reset to default 8

I 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