在JavaScript中,可以通过监听页面的visibilitychange
事件以及使用performance.now()
方法来统计页面停留时长。
一、基础概念
visibilitychange
事件performance.now()
方法二、示例代码
let startTime;
let totalDuration = 0;
document.addEventListener('visibilitychange', function () {
if (document.visibilityState === 'visible') {
startTime = performance.now();
} else if (document.visibilityState === 'hidden') {
if (startTime) {
const endTime = performance.now();
totalDuration += endTime - startTime;
startTime = null;
}
}
});
// 如果需要在页面卸载时也统计一下(防止用户直接关闭浏览器等情况)
window.addEventListener('beforeunload', function () {
if (startTime) {
const endTime = performance.now();
totalDuration += endTime - startTime;
}
console.log('页面停留时长(毫秒):', totalDuration);
});
三、优势
performance.now()
的高精度时间戳,可以较为准确地计算出页面在可见状态下的停留时间。visibilitychange
事件和performance.now()
方法在现代浏览器中都有很好的支持。四、应用场景
五、可能出现的问题及解决方法
performance.now()
精度较高,但在一些极端情况下(如系统时间突然调整),可能会产生小的误差。解决方法是尽量在合理的逻辑范围内使用,并且可以考虑多次测量取平均值等策略来减少误差影响。领取专属 10元无门槛券
手把手带您无忧上云