Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i update database on browser window close?

I am trying to stream some videos to users and i want to enable them to resume watching a video when they leave the website and enter again. As far as i know storing the video time in browser's local storage and retrieving it when they come back is the best way, but in this case, when the user logins from different PC or browser the video watched time resets. As synchronous Ajax is disabled in some browsers now, I also can't save the watched time in database on browser close (using onunload or beforeunload events).

Another way i have tried is, to save the time when user clicks on pause button like this:

var video1 = document.getElementById('video1');

function videoPausePlayHandler(e) {
    if (e.type == 'pause') {
        //saving the watched time in databse using Ajax
    }
}
video1.addEventListener('pause', videoPausePlayHandler, false);

But again when user closes the browser window or anything else rather than clicking on pause button, it won't work.

Is there any other way to do this?

like image 641
Arman Jelodar Avatar asked Oct 16 '22 02:10

Arman Jelodar


1 Answers

You can use the browser’s onunload event and send a Navigator.sendBeacon to asynchronously send your timestamp to your server without blocking the user from closing the browser window. sendBeacon Documentation. The Browser coverage looks quite good. Just the old IE does not support it at all.

like image 132
sebastian-ruehmann Avatar answered Oct 25 '22 05:10

sebastian-ruehmann