经常会有一些在用户离开页面前执行一些业务的应用场景,这都要用到 onbeforeunload 事件;比如记录用户停留时长的业务,在 GA 等页面访问统计的应用中都包含这个:
;(function(){
var startTime = Math.ceil(new Date().getTime()/1000), //单位秒
getDuration = function(){
var time = ”,
hours = 0,
minutes = 0,
seconds = 0,
endTime = Math.ceil(new Date().getTime()/1000),
duration = endTime – startTime;
hours = Math.floor(duration/3600); //停留小时数
minutes = Math.floor(duration%3600/60); //停留分钟数
seconds = Math.floor(duration%3600%60); //停留秒数
time = (hours < 10 ? '0' + hours : hours) + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds);
return time;
};
window.onbeforeunload = function(e){
var duration = getDuration();
//request(duration);
};
})();
Warn
Warn
3年前 (2017-12-19)
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/198734.html原文链接:https://javaforall.net
