Skip to content Skip to sidebar Skip to footer

Save Html5 Video Currenttime Before User Leaves Or Closes Page

I would like to save the position of HTML5 video's currentTime to the database when user leaves a web page. It seems like window.onbeforeunload is not a reliable way to do it (not

Solution 1:

There are various ways to save such things:

Locally (for the same domain)

beforeunload

This gives you the possibility to cancel the unload event if you desire. However, the popup is optional.

unload

This event can't be cancelled but you still have full access to all nodes and JavaScript variables. So you can do final cleanup/save then if canceling is not wanted. You can use whichever saving method you like, e.g. document.cookie or window.localStorage.

window.onunload = function () {
    window.localstorage[myVideo.currentTime] = document.getElementById("myVid").currentTime;
}

If you can handle the fact that you can only process cookies and localStorage when the user comes back to your site. I think this approach would be perfect. You simply save the current time and on the users next visit you'll get the updated information.

On the Backend

If you really need to save that information to your backend you can try some other things.

DB polling

Depending on you accuracy needs you could send an ajax request every 10 - 20 seconds to update the playback time. If you just include the video id and current time, the request is so small it shouldn't have an effect on performance. However keep in mind that if you have lots of domain cookies it might increase the size of requests tremendously and your 500 byte payload might come with a 5kB header.

Post a Comment for "Save Html5 Video Currenttime Before User Leaves Or Closes Page"