Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 290
Jscti Avatar asked Sep 04 '18 10:09

Jscti


People also ask

Which event triggers when the user leaves the page?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.

How can you tell if someone leaves your page?

The most reliable way to detect when a user leaves a web page is to use visiblitychange event. This event will fire to even the slightest changes like changing tabs, minimizing the browser, switching from browser to another app on mobile, etc.


1 Answers

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);
like image 77
Josh Avatar answered Sep 28 '22 07:09

Josh