我正在使用带有自定义脚本的 VideoJS,该脚本通过 AJAX 将值发布回数据库。当视频暂停时,它将观看视频的百分比放入数据库。
这一切都很好,除了一件事。如果他们只是在观看视频时离开页面,则不会记录他们离开的时间点。
从我的研究看来,我应该使用 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;
});
});
我可以创建一个自定义事件侦听器来放置他们离开页面时观看的当前视频百分比吗?