我正在使用带有自定义脚本的VideoJS,该脚本通过AJAX将值发布回数据库。当视频暂停时,它会将观看视频的百分比PUT到数据库中。
这一切都很有效,除了一件事。如果他们在观看视频时离开页面,则不会记录他们离开的位置。
从我的研究看起来我应该使用window.onbeforeunload来更新paused_at字段,但我无法弄清楚如何创建自定义监听器。
这是我的代码。
$(document).ready(function() {
videojs("video" + videoId, {
// Video player options
"controls":true,
"autoplay":false,
"preload": "auto",
"width": "100%",
"height": "400px"
}).ready(function() {
// Bring our object into scope
var video = this;
// Time that they start watching the video
var started_at = function() {
var video_percent = calc_percent(video.currentTime(), video.duration());
var data = {
"id": videoId,
"user": userId,
"started_at": video_percent
};
ajax_post(data);
};
// Video was paused
var paused_at = function() {
var video_percent = calc_percent(video.currentTime(), video.duration());
var data = {
"id": videoId,
"user": userId,
"paused_at": video_percent
};
ajax_post(data);
};
// Video is completed
var finished_at = function() {
var data = {
"id": videoId,
"user": userId,
"finished_at": true
};
ajax_post(data);
};
// Post our data to the update route
var ajax_post = function(data) {
console.log(data);
$.ajax({
type: 'PUT',
url: '/videoAPI',
dataType: 'json',
data: data
});
};
var calc_percent = function(progress, total) {
var percent = (progress / total) * 100;
return percent.toFixed(2);
}
// Listen for event and fire the right method
video.on("play", started_at);
video.on("pause", paused_at);
video.on("ended", finished_at);
window.onbeforeunload = paused_at;
});
});
我可以创建一个自定义事件监听器来PUT当他们离开页面时观看的当前视频百分比吗?
答案 0 :(得分:0)
window.onbeforeunload = paused_at;
。
$(window).on('beforeunload', paused_at);