0
我正在使用VideoJS和自定義腳本,通過AJAX將值發送回數據庫。當視頻暫停時,它會將觀看視頻的百分比放到數據庫中。VideoJS離開頁面的事件
除了一件事外,這一切都很好。如果他們只是在觀看視頻時離開頁面,則不會記錄他們離開的地點。
從我的研究看來,我應該使用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當他們離開頁面時觀看的視頻的當前百分比嗎?
我已經嘗試了一些這方面的變化。 '$(window).on('unload',paused_at); ' '$(window).on('beforeunload',paused_at); ' '$(window).unload(paused_at); ' 雖然他們開火事件。沒有數據寫入數據庫。它可能會跳過ajax函數嗎? – gerobk