Save HTML5 video currentTime before user leaves or closes page

流过昼夜 提交于 2019-12-04 14:56:07

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!