在前端監(jiān)控用戶在當(dāng)前界面的停留時(shí)長(也稱為“頁面停留時(shí)間”或“Dwell Time”)是用戶行為分析中非常重要的指標(biāo)。它可以幫助我們了解用戶對某個(gè)頁面的興趣程度、內(nèi)容質(zhì)量以及用戶體驗(yàn)。
停留時(shí)長監(jiān)控的挑戰(zhàn)
監(jiān)控停留時(shí)長并非簡單地計(jì)算進(jìn)入和離開的時(shí)間差,因?yàn)樗枰紤]多種復(fù)雜情況:
- 用戶切換標(biāo)簽頁或最小化瀏覽器: 頁面可能仍在后臺(tái)運(yùn)行,但用戶并未真正“停留”在該界面。
- 瀏覽器關(guān)閉或崩潰: 頁面沒有正常卸載,可能無法觸發(fā)
unload
事件。 - 網(wǎng)絡(luò)問題: 數(shù)據(jù)上報(bào)可能失敗。
- 單頁應(yīng)用 (SPA) : 在 SPA 中,頁面切換不會(huì)觸發(fā)傳統(tǒng)的頁面加載和卸載事件,需要監(jiān)聽路由變化。
- 長時(shí)間停留: 如果用戶停留時(shí)間很長,一次性上報(bào)可能導(dǎo)致數(shù)據(jù)丟失(例如,瀏覽器或電腦崩潰)。
實(shí)現(xiàn)監(jiān)測的思路和方法
我們將結(jié)合多種 Web API 來實(shí)現(xiàn)一個(gè)健壯的停留時(shí)長監(jiān)控方案。
1. 基礎(chǔ)方案:頁面加載與卸載 (適用于傳統(tǒng)多頁應(yīng)用)
這是最基本的方案,通過記錄頁面加載時(shí)間和卸載時(shí)間來計(jì)算停留時(shí)長。
let startTime = 0;
let pageId = '';
function sendPageDuration(id, duration, isUnload = false) {
const data = {
pageId: id,
duration: duration,
timestamp: Date.now(),
eventType: isUnload ? 'page_unload' : 'page_hide',
userAgent: navigator.userAgent,
screenWidth: window.screen.width,
screenHeight: window.screen.height
};
console.log('上報(bào)頁面停留時(shí)長:', data);
if (navigator.sendBeacon) {
navigator.sendBeacon('/api/page-duration', JSON.stringify(data));
} else {
fetch('/api/page-duration', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
keepalive: true
}).catch(e => console.error('發(fā)送停留時(shí)長失敗:', e));
}
}
window.addEventListener('load', () => {
startTime = Date.now();
pageId = window.location.pathname;
console.log(`頁面 ${pageId} 加載,開始計(jì)時(shí): ${startTime}`);
});
window.addEventListener('pagehide', () => {
if (startTime > 0) {
const duration = Date.now() - startTime;
sendPageDuration(pageId, duration, true);
startTime = 0;
}
});
window.addEventListener('beforeunload', () => {
if (startTime > 0) {
const duration = Date.now() - startTime;
sendPageDuration(pageId, duration, true);
startTime = 0;
}
});
代碼講解:
startTime
: 記錄頁面加載時(shí)的 Unix 時(shí)間戳。
pageId
: 標(biāo)識當(dāng)前頁面,這里簡單地使用了 window.location.pathname
。在實(shí)際應(yīng)用中,你可能需要更復(fù)雜的 ID 策略(如路由名稱、頁面 ID 等)。
sendPageDuration(id, duration, isUnload)
: 負(fù)責(zé)將頁面 ID 和停留時(shí)長發(fā)送到后端。
navigator.sendBeacon()
: 推薦用于在頁面卸載時(shí)發(fā)送數(shù)據(jù)。它不會(huì)阻塞頁面卸載,且即使頁面正在關(guān)閉,也能保證數(shù)據(jù)發(fā)送。fetch({ keepalive: true })
: keepalive: true
選項(xiàng)允許 fetch
請求在頁面卸載后繼續(xù)發(fā)送,作為 sendBeacon
的備用方案。
window.addEventListener('load', ...)
: 在頁面完全加載后開始計(jì)時(shí)。
window.addEventListener('pagehide', ...)
: 當(dāng)用戶離開頁面(切換標(biāo)簽頁、關(guān)閉瀏覽器、導(dǎo)航到其他頁面)時(shí)觸發(fā)。這是一個(gè)更可靠的事件,尤其是在移動(dòng)端,因?yàn)樗陧撁孢M(jìn)入“后臺(tái)”狀態(tài)時(shí)觸發(fā)。
window.addEventListener('beforeunload', ...)
: 在頁面即將卸載時(shí)觸發(fā)。它比 pagehide
觸發(fā)得更早,但可能會(huì)被瀏覽器阻止(例如,如果頁面有未保存的更改)。作為補(bǔ)充使用。
2. 考慮用戶活躍狀態(tài):Visibility API
當(dāng)用戶切換標(biāo)簽頁或最小化瀏覽器時(shí),頁面可能仍在運(yùn)行,但用戶并未真正“停留”。document.visibilityState
和 visibilitychange
事件可以幫助我們識別這種狀態(tài)。
let startTime = 0;
let totalActiveTime = 0;
let lastActiveTime = 0;
let pageId = '';
function sendPageDuration(id, duration, eventType) {
const data = {
pageId: id,
duration: duration,
timestamp: Date.now(),
eventType: eventType,
};
console.log('上報(bào)頁面停留時(shí)長:', data);
if (navigator.sendBeacon) {
navigator.sendBeacon('/api/page-duration', JSON.stringify(data));
} else {
fetch('/api/page-duration', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), keepalive: true }).catch(e => console.error('發(fā)送停留時(shí)長失敗:', e));
}
}
function startTracking() {
startTime = Date.now();
lastActiveTime = startTime;
totalActiveTime = 0;
pageId = window.location.pathname;
console.log(`頁面 ${pageId} 加載,開始計(jì)時(shí) (總時(shí)長): ${startTime}`);
}
function stopTrackingAndReport(eventType) {
if (startTime > 0) {
if (document.visibilityState === 'visible') {
totalActiveTime += (Date.now() - lastActiveTime);
}
sendPageDuration(pageId, totalActiveTime, eventType);
startTime = 0;
totalActiveTime = 0;
lastActiveTime = 0;
}
}
window.addEventListener('load', startTracking);
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
totalActiveTime += (Date.now() - lastActiveTime);
console.log(`頁面 ${pageId} 變?yōu)椴豢梢姡奂踊钴S時(shí)間: ${totalActiveTime}`);
} else {
lastActiveTime = Date.now();
console.log(`頁面 ${pageId} 變?yōu)榭梢姡謴?fù)計(jì)時(shí): ${lastActiveTime}`);
}
});
window.addEventListener('pagehide', () => stopTrackingAndReport('page_hide'));
window.addEventListener('beforeunload', () => stopTrackingAndReport('page_unload'));
let heartbeatInterval;
window.addEventListener('load', () => {
startTracking();
heartbeatInterval = setInterval(() => {
if (document.visibilityState === 'visible' && startTime > 0) {
const currentActiveTime = Date.now() - lastActiveTime;
totalActiveTime += currentActiveTime;
lastActiveTime = Date.now();
console.log(`心跳上報(bào) ${pageId} 活躍時(shí)間: ${currentActiveTime}ms, 累計(jì): ${totalActiveTime}ms`);
sendPageDuration(pageId, currentActiveTime, 'heartbeat');
}
}, 30 * 1000);
});
window.addEventListener('pagehide', () => {
clearInterval(heartbeatInterval);
stopTrackingAndReport('page_hide');
});
window.addEventListener('beforeunload', () => {
clearInterval(heartbeatInterval);
stopTrackingAndReport('page_unload');
});
代碼講解:
totalActiveTime
: 存儲(chǔ)用戶在頁面可見狀態(tài)下的累計(jì)停留時(shí)間。
lastActiveTime
: 記錄頁面上次變?yōu)榭梢姷臅r(shí)間戳。
document.addEventListener('visibilitychange', ...)
: 監(jiān)聽頁面可見性變化。
- 當(dāng)頁面變?yōu)?nbsp;
hidden
時(shí),將從 lastActiveTime
到當(dāng)前的時(shí)間差累加到 totalActiveTime
。 - 當(dāng)頁面變?yōu)?nbsp;
visible
時(shí),更新 lastActiveTime
為當(dāng)前時(shí)間,表示重新開始計(jì)算活躍時(shí)間。
心跳上報(bào): setInterval
每隔一段時(shí)間(例如 30 秒)檢查頁面是否可見,如果是,則計(jì)算并上報(bào)當(dāng)前時(shí)間段的活躍時(shí)間。這有助于在用戶長時(shí)間停留但未觸發(fā) pagehide
或 beforeunload
的情況下(例如瀏覽器崩潰、電腦關(guān)機(jī)),也能獲取到部分停留數(shù)據(jù)。
3. 針對單頁應(yīng)用 (SPA) 的解決方案
SPA 的頁面切換不會(huì)觸發(fā)傳統(tǒng)的 load
或 unload
事件。我們需要監(jiān)聽路由變化來模擬頁面的“加載”和“卸載”。
let startTime = 0;
let totalActiveTime = 0;
let lastActiveTime = 0;
let currentPageId = '';
function sendPageDuration(id, duration, eventType) {
const data = {
pageId: id,
duration: duration,
timestamp: Date.now(),
eventType: eventType,
};
console.log('上報(bào) SPA 頁面停留時(shí)長:', data);
if (navigator.sendBeacon) {
navigator.sendBeacon('/api/page-duration', JSON.stringify(data));
} else {
fetch('/api/page-duration', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), keepalive: true }).catch(e => console.error('發(fā)送停留時(shí)長失敗:', e));
}
}
function startTrackingNewPage(newPageId) {
if (currentPageId && startTime > 0) {
if (document.visibilityState === 'visible') {
totalActiveTime += (Date.now() - lastActiveTime);
}
sendPageDuration(currentPageId, totalActiveTime, 'route_change');
}
startTime = Date.now();
lastActiveTime = startTime;
totalActiveTime = 0;
currentPageId = newPageId;
console.log(`SPA 頁面 ${currentPageId} 加載,開始計(jì)時(shí): ${startTime}`);
}
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
totalActiveTime += (Date.now() - lastActiveTime);
console.log(`SPA 頁面 ${currentPageId} 變?yōu)椴豢梢?,累加活躍時(shí)間: ${totalActiveTime}`);
} else {
lastActiveTime = Date.now();
console.log(`SPA 頁面 ${currentPageId} 變?yōu)榭梢?,恢?fù)計(jì)時(shí): ${lastActiveTime}`);
}
});
window.addEventListener('popstate', () => {
startTrackingNewPage(window.location.pathname);
});
const originalPushState = history.pushState;
history.pushState = function() {
originalPushState.apply(history, arguments);
startTrackingNewPage(window.location.pathname);
};
const originalReplaceState = history.replaceState;
history.replaceState = function() {
originalReplaceState.apply(history, arguments);
};
window.addEventListener('load', () => {
startTrackingNewPage(window.location.pathname);
});
window.addEventListener('pagehide', () => {
if (currentPageId && startTime > 0) {
if (document.visibilityState === 'visible') {
totalActiveTime += (Date.now() - lastActiveTime);
}
sendPageDuration(currentPageId, totalActiveTime, 'app_unload');
currentPageId = '';
startTime = 0;
totalActiveTime = 0;
lastActiveTime = 0;
}
});
window.addEventListener('beforeunload', () => {
if (currentPageId && startTime > 0) {
if (document.visibilityState === 'visible') {
totalActiveTime += (Date.now() - lastActiveTime);
}
sendPageDuration(currentPageId, totalActiveTime, 'app_unload');
currentPageId = '';
startTime = 0;
totalActiveTime = 0;
lastActiveTime = 0;
}
});
let heartbeatInterval;
window.addEventListener('load', () => {
heartbeatInterval = setInterval(() => {
if (document.visibilityState === 'visible' && currentPageId) {
const currentActiveTime = Date.now() - lastActiveTime;
totalActiveTime += currentActiveTime;
lastActiveTime = Date.now();
console.log(`SPA 心跳上報(bào) ${currentPageId} 活躍時(shí)間: ${currentActiveTime}ms, 累計(jì): ${totalActiveTime}ms`);
sendPageDuration(currentPageId, currentActiveTime, 'heartbeat');
}
}, 30 * 1000);
});
window.addEventListener('pagehide', () => clearInterval(heartbeatInterval));
window.addEventListener('beforeunload', () => clearInterval(heartbeatInterval));
代碼講解:
總結(jié)與最佳實(shí)踐
- 區(qū)分多頁應(yīng)用和單頁應(yīng)用: 根據(jù)你的應(yīng)用類型選擇合適的監(jiān)聽策略。
- 結(jié)合 Visibility API: 確保只計(jì)算用戶真正“活躍”在頁面上的時(shí)間。
- 使用
navigator.sendBeacon
: 確保在頁面卸載時(shí)數(shù)據(jù)能夠可靠上報(bào)。 - 心跳上報(bào): 對于長時(shí)間停留的頁面,定期上報(bào)數(shù)據(jù),防止數(shù)據(jù)丟失。
- 唯一頁面標(biāo)識: 確保每個(gè)頁面都有一個(gè)唯一的 ID,以便后端能夠正確聚合數(shù)據(jù)。
- 上下文信息: 上報(bào)數(shù)據(jù)時(shí),包含用戶 ID、會(huì)話 ID、設(shè)備信息、瀏覽器信息等,以便更深入地分析用戶行為。
- 后端處理: 后端需要接收這些數(shù)據(jù),并進(jìn)行存儲(chǔ)、聚合和分析。例如,可以計(jì)算每個(gè)頁面的平均停留時(shí)間、總停留時(shí)間、不同用戶群體的停留時(shí)間等。
- 數(shù)據(jù)準(zhǔn)確性: 即使有了這些方案,停留時(shí)長仍然是一個(gè)近似值,因?yàn)榭傆幸恍O端情況(如斷網(wǎng)、瀏覽器崩潰)可能導(dǎo)致數(shù)據(jù)丟失。目標(biāo)是盡可能提高數(shù)據(jù)的準(zhǔn)確性和覆蓋率。
轉(zhuǎn)自https://juejin.cn/post/7510803578505134119
該文章在 2025/6/4 11:59:09 編輯過