function PageView(option) { this.entry_time = [], this.hidden_time = [], this.split_time = [], this.stay_time = 0,
this.closeCb = option.closeCb || null this.init(); } PageView.prototype.countEntryTime = function () { this.entry_time.push(new Date().getTime()); }; PageView.prototype.countHiddenTime = function () { this.hidden_time.push(new Date().getTime()); }; PageView.prototype.getAnalysisData = function () { let aEntryTime = this.entry_time, aHiddenTime = this.hidden_time; for (let i = 0; i < aHiddenTime.length; i++) { let t = +(aHiddenTime[i] - aEntryTime[i]) this.split_time.push(t); } let nStayTime = 0; for (let i = 0; i < this.split_time.length; i++) { nStayTime += this.split_time[i]; }; nStayTime = +nStayTime.toFixed(0); this.stay_time = nStayTime; return { split_time: this.split_time, stay_time: this.stay_time } }; PageView.prototype.setAnalysis = function () { let data = this.getAnalysisData(); if (data.stay_time) { this.closeCb && this.closeCb(data, window.history.length); } else { console.error('停留时间计算错误'); } }; PageView.prototype.initCloseWindow = function () { let self = this; window.addEventListener("beforeunload", function (event) { self.countHiddenTime(); self.setAnalysis(); }); }; PageView.prototype.initChangeVisible = function () { let self = this; function handleVisibilityChange() { if (document[hidden]) { self.countHiddenTime(); } else { self.countEntryTime(); } } var hidden, visibilityChange; if (typeof document.hidden !== "undefined") { hidden = "hidden"; visibilityChange = "visibilitychange"; } else if (typeof document.msHidden !== "undefined") { hidden = "msHidden"; visibilityChange = "msvisibilitychange"; } else if (typeof document.webkitHidden !== "undefined") { hidden = "webkitHidden"; visibilityChange = "webkitvisibilitychange"; } if (document.addEventListener) { document.addEventListener(visibilityChange, handleVisibilityChange, false); } else { document.attachEvent('on' + visibilityChange, handleVisibilityChange); } }; PageView.prototype.init = function () { this.countEntryTime(); this.initChangeVisible(); this.initCloseWindow(); }; module.exports = PageView;