網頁功能:
網頁瀏覽狀態效能項目
本指南將詳細說明如何準確計算使用者主動瀏覽網頁的總時間。傳統指標 (例如網頁停留時間) 通常會錯誤地將網頁在背景執行的時間納入計算。使用 VisibilityStateEntry API,您只能評估「前景時間」,提供更準確的使用者參與度指標。
實作前景時間計算
PerformanceTimeline API 會將瀏覽權限狀態變更公開為效能項目。您不必對 visibilitychange 事件做出反應,也不必在整個工作階段中手動累積時間,而是可以隨時查詢整個可見度記錄。
必要:您必須查詢 visibility-state 效能項目,才能計算實際的前景時間。
/**
* Calculates total time the page was in the visible state.
*
* @returns {number} Total foreground time in milliseconds.
*/
function getTotalForegroundTime() {
// MANDATORY: Query the visibility-state entries from the performance timeline.
const entries = performance.getEntriesByType('visibility-state');
// Fallback: If the browser does not support VisibilityStateEntry,
// the API will gracefully return an empty array.
if (entries.length === 0) {
// Return total time since navigation start as a fallback.
return performance.now();
}
let totalForegroundTime = 0;
for (let i = 0; i < entries.length; i++) {
// Only calculate duration for periods where the state was 'visible'
if (entries[i].name === 'visible') {
const start = entries[i].startTime;
// The end time is the start time of the next state change,
// or the current time if this is the final entry.
const end = i + 1 < entries.length
? entries[i + 1].startTime
: performance.now();
totalForegroundTime += (end - start);
}
}
return totalForegroundTime;
}
備用方案和瀏覽器支援
VisibilityStateEntry API 是 Performance Timeline 的新功能,可能不支援所有瀏覽器。
由於 performance.getEntriesByType('visibility-state') 在不支援的瀏覽器中會傳回空白陣列,因此功能偵測會內建在計算流程中。請務必先確認是否傳回項目,再繼續操作。
如果系統不支援 API,建議改為傳回 performance.now()。這代表自導覽以來經過的總時間,在無法取得瀏覽權限狀態記錄時,可做為參與時間的合理上限。
const entries = performance.getEntriesByType('visibility-state');
// If the array is empty, the API is likely unsupported.
if (entries.length === 0) {
// Fallback: Return total time since page load.
return performance.now();
}