在前端監控用戶在當前界面的停留時長(也稱為“頁面停留時間”或“Dwell Time”)是用戶行為分析中非常重要的指標。它可以幫助我們了解用戶對某個頁面的興趣程度、內容質量以及用戶體驗。
停留時長監控的挑戰
監控停留時長并非簡單地計算進入和離開的時間差,因為它需要考慮多種復雜情況:
- 用戶切換標簽頁或最小化瀏覽器: 頁面可能仍在后臺運行,但用戶并未真正“停留”在該界面。
- 瀏覽器關閉或崩潰: 頁面沒有正常卸載,可能無法觸發
unload
事件。 - 網絡問題: 數據上報可能失敗。
- 單頁應用 (SPA) : 在 SPA 中,頁面切換不會觸發傳統的頁面加載和卸載事件,需要監聽路由變化。
- 長時間停留: 如果用戶停留時間很長,一次性上報可能導致數據丟失(例如,瀏覽器或電腦崩潰)。
實現監測的思路和方法
我們將結合多種 Web API 來實現一個健壯的停留時長監控方案。
1. 基礎方案:頁面加載與卸載 (適用于傳統多頁應用)
這是最基本的方案,通過記錄頁面加載時間和卸載時間來計算停留時長。
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('上報頁面停留時長:', 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('發送停留時長失敗:', e));
}
}
window.addEventListener('load', () => {
startTime = Date.now();
pageId = window.location.pathname;
console.log(`頁面 ${pageId} 加載,開始計時: ${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
: 記錄頁面加載時的 Unix 時間戳。
pageId
: 標識當前頁面,這里簡單地使用了 window.location.pathname
。在實際應用中,你可能需要更復雜的 ID 策略(如路由名稱、頁面 ID 等)。
sendPageDuration(id, duration, isUnload)
: 負責將頁面 ID 和停留時長發送到后端。
navigator.sendBeacon()
: 推薦用于在頁面卸載時發送數據。它不會阻塞頁面卸載,且即使頁面正在關閉,也能保證數據發送。fetch({ keepalive: true })
: keepalive: true
選項允許 fetch
請求在頁面卸載后繼續發送,作為 sendBeacon
的備用方案。
window.addEventListener('load', ...)
: 在頁面完全加載后開始計時。
window.addEventListener('pagehide', ...)
: 當用戶離開頁面(切換標簽頁、關閉瀏覽器、導航到其他頁面)時觸發。這是一個更可靠的事件,尤其是在移動端,因為它在頁面進入“后臺”狀態時觸發。
window.addEventListener('beforeunload', ...)
: 在頁面即將卸載時觸發。它比 pagehide
觸發得更早,但可能會被瀏覽器阻止(例如,如果頁面有未保存的更改)。作為補充使用。
2. 考慮用戶活躍狀態:Visibility API
當用戶切換標簽頁或最小化瀏覽器時,頁面可能仍在運行,但用戶并未真正“停留”。document.visibilityState
和 visibilitychange
事件可以幫助我們識別這種狀態。
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('上報頁面停留時長:', 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('發送停留時長失敗:', e));
}
}
function startTracking() {
startTime = Date.now();
lastActiveTime = startTime;
totalActiveTime = 0;
pageId = window.location.pathname;
console.log(`頁面 ${pageId} 加載,開始計時 (總時長): ${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} 變為不可見,累加活躍時間: ${totalActiveTime}`);
} else {
lastActiveTime = Date.now();
console.log(`頁面 ${pageId} 變為可見,恢復計時: ${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(`心跳上報 ${pageId} 活躍時間: ${currentActiveTime}ms, 累計: ${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
: 存儲用戶在頁面可見狀態下的累計停留時間。
lastActiveTime
: 記錄頁面上次變為可見的時間戳。
document.addEventListener('visibilitychange', ...)
: 監聽頁面可見性變化。
- 當頁面變為
hidden
時,將從 lastActiveTime
到當前的時間差累加到 totalActiveTime
。 - 當頁面變為
visible
時,更新 lastActiveTime
為當前時間,表示重新開始計算活躍時間。
心跳上報: setInterval
每隔一段時間(例如 30 秒)檢查頁面是否可見,如果是,則計算并上報當前時間段的活躍時間。這有助于在用戶長時間停留但未觸發 pagehide
或 beforeunload
的情況下(例如瀏覽器崩潰、電腦關機),也能獲取到部分停留數據。
3. 針對單頁應用 (SPA) 的解決方案
SPA 的頁面切換不會觸發傳統的 load
或 unload
事件。我們需要監聽路由變化來模擬頁面的“加載”和“卸載”。
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('上報 SPA 頁面停留時長:', 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('發送停留時長失敗:', 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} 加載,開始計時: ${startTime}`);
}
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
totalActiveTime += (Date.now() - lastActiveTime);
console.log(`SPA 頁面 ${currentPageId} 變為不可見,累加活躍時間: ${totalActiveTime}`);
} else {
lastActiveTime = Date.now();
console.log(`SPA 頁面 ${currentPageId} 變為可見,恢復計時: ${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 心跳上報 ${currentPageId} 活躍時間: ${currentActiveTime}ms, 累計: ${totalActiveTime}ms`);
sendPageDuration(currentPageId, currentActiveTime, 'heartbeat');
}
}, 30 * 1000);
});
window.addEventListener('pagehide', () => clearInterval(heartbeatInterval));
window.addEventListener('beforeunload', () => clearInterval(heartbeatInterval));
代碼講解:
總結與最佳實踐
- 區分多頁應用和單頁應用: 根據你的應用類型選擇合適的監聽策略。
- 結合 Visibility API: 確保只計算用戶真正“活躍”在頁面上的時間。
- 使用
navigator.sendBeacon
: 確保在頁面卸載時數據能夠可靠上報。 - 心跳上報: 對于長時間停留的頁面,定期上報數據,防止數據丟失。
- 唯一頁面標識: 確保每個頁面都有一個唯一的 ID,以便后端能夠正確聚合數據。
- 上下文信息: 上報數據時,包含用戶 ID、會話 ID、設備信息、瀏覽器信息等,以便更深入地分析用戶行為。
- 后端處理: 后端需要接收這些數據,并進行存儲、聚合和分析。例如,可以計算每個頁面的平均停留時間、總停留時間、不同用戶群體的停留時間等。
- 數據準確性: 即使有了這些方案,停留時長仍然是一個近似值,因為總有一些極端情況(如斷網、瀏覽器崩潰)可能導致數據丟失。目標是盡可能提高數據的準確性和覆蓋率。
轉自https://juejin.cn/post/7510803578505134119
該文章在 2025/6/4 11:59:09 編輯過