如何用JS監控網絡流量

如何用JS監控網絡流量

本文介紹如何利用JavaScript的Performance API監控網頁網絡流量。Performance API提供網頁性能的詳細信息,包括網絡請求的時間線數據。

監控網絡流量步驟:

  1. 獲取性能數據: 使用performance.getEntries()或performance.getEntriesByType()方法獲取性能條目。
  2. 識別網絡請求: 遍歷性能條目,檢查entryType屬性是否為’Resource’,以篩選出網絡請求。
  3. 提取關鍵信息: 從每個網絡請求條目中提取所需數據,例如請求URL、起始時間、響應時間、傳輸大小等。

以下示例代碼演示如何監控頁面加載過程中的網絡流量:

window.onload = function() {     const entries = performance.getEntries();     entries.forEach(entry => {         if (entry.entryType === 'resource') {             console.log('資源名稱:', entry.name);             console.log('起始時間:', entry.startTime);             console.log('持續時間:', entry.responseEnd - entry.startTime);             console.log('傳輸大小:', entry.transferSize);             console.log('編碼后大小:', entry.encodedBodySize);             console.log('解碼后大小:', entry.decodedBodySize);             console.log('---');         }     }); };

performance.getEntries()返回包含所有性能條目的數組。 若需更精細控制,performance.getEntriesByType(‘resource’) 可直接獲取僅包含資源請求的數組。

實時監控: 要實時監控,需定期調用這些方法并計算兩次調用結果的差值。

兼容性及限制: 請注意,出于隱私和安全考慮,某些瀏覽器可能限制或禁用Performance API的某些功能。 使用前請務必測試兼容性。

? 版權聲明
THE END
喜歡就支持一下吧
點贊7 分享