在用户离开或关闭页面之前保存HTML5视频currentTime [英] Save HTML5 video currentTime before user leaves or closes page

查看:143
本文介绍了在用户离开或关闭页面之前保存HTML5视频currentTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户离开网页时,我想将HTML5视频的 currentTime 的位置保存到数据库中。似乎 window.onbeforeunload 不是一种可行的方法(更不用说它会给出一个不合需要的弹出窗口!)。有没有更好的方法呢?

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 to mention it gives an undesirable popup window!). Is there a better way to do this?

除了定期将位置保存到服务器外,我想不出什么。但这似乎是浪费资源/带宽的明智之举。 Netflix似乎在记住你上次观看的位置方面做得很好。他们如何能够可靠地实现这一目标?低级服务器端C / C ++代码可能?

I can't think of anything other than saving the position to the server periodically. But that seems wasteful resource/bandwidth wise. Netflix seems to do a good job at remembering your last viewed position. How would they be able to achieve that reliably? Low-level server-side C/C++ code maybe?

推荐答案

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

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.

这篇关于在用户离开或关闭页面之前保存HTML5视频currentTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆