且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在用户离开或关闭页面之前保存HTML5视频currentTime

更新时间:2023-12-01 20:09:40

有多种方法可以保存这些东西:

There are various ways to save such things:

这如果您愿意,可以取消卸载事件。但是,弹出窗口是可选的。

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

此活动无法取消但您仍然已满访问所有节点和JavaScript变量。因此,如果不需要取消,您可以进行最终清理/保存。您可以使用任何您喜欢的保存方法,例如 document.cookie window.localStorage

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

如果你能处理的事实是你只能处理cookies和localStorage用户回到您的网站。我认为这种方法是完美的。您只需保存当前时间,下次访问的用户就可以获得更新的信息。

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.

如果你真的需要将这些信息保存到你的后端,你可以尝试其他一些事情。

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

根据您的准确度需求,您可以每10到20秒发送一次ajax请求以更新播放时间。如果您只包含视频ID和当前时间,则请求非常小,不应对性能产生影响。但是请记住,如果你有很多域cookie,它可能会极大地增加请求的大小,而你的500字节有效载荷可能带有5kB的头。

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.