Jscti
Jscti

Reputation: 14440

Is there an event to detect when user interacted with a page?

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 ...

Upvotes: 13

Views: 7277

Answers (2)

Josh
Josh

Reputation: 918

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);

Upvotes: 8

kockburn
kockburn

Reputation: 17626

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);
      }
      
    }
  }); 
});

Upvotes: -1

Related Questions