如何使用 CrUX API

瞭解如何使用 Chrome UX Report API,存取數百萬個網站上的實際使用者體驗資料。

Shane Exterkamp
Shane Exterkamp

Chrome 使用者體驗報告 (CrUX) 資料集呈現了 Chrome 使用者實際體驗熱門網路目的地的情況。自 2017 年起,我們首次在 BigQuery 發布可查詢的資料集,因此 CrUX 中的欄位資料現已整合至開發人員工具,例如 PageSpeed InsightsCrUX 資訊主頁和 Search Console 的Core Web Vitals 報表,因此開發人員可以評估及監控實際使用者體驗。這次一直都遺漏了一項工具,能讓使用者以程式輔助方式免費且符合 REST 樣式存取 CrUX 資料。為瞭解決這個問題,我們很高興宣布推出全新的 Chrome UX Report API

這個 API 的設計宗旨,是要為開發人員提供簡單、快速且全面的 CrUX 資料。CrUX API 只會回報使用者體驗欄位的資料,與現有的 PageSpeed Insights API 不同。後者也會回報 Lighthouse 效能稽核結果的研究室資料。CrUX API 運作得宜,且能快速提供使用者體驗資料,非常適合用於即時稽核應用程式。

為確保開發人員能存取所有最重要的指標,也就是 Core Web Vitals。透過 CrUX API 進行稽核,並在來源和網址層級監控最大內容繪製 (LCP)、首次輸入延遲時間 (FID) 和累計版面配置位移 (CLS)。

現在就讓我們一探究竟,瞭解使用方式!

查詢來源資料

CrUX 資料集的來源涵蓋所有基礎網頁層級體驗。以下範例說明如何在指令列中使用 cURL,查詢 CrUX API,找出來源的使用者體驗資料。

API_KEY="[YOUR_API_KEY]"
curl "https://chromeuxreport.googleapis.com/v1/records:queryRecord?key=$API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{"origin": "https://web.dev"}'
敬上

curl 指令由三個部分組成:

  1. API 的網址端點,包括呼叫端的私人 API 金鑰。
  2. Content-Type: application/json 標頭,表示要求主體包含 JSON。
  3. 採用 JSON 編碼的要求主體,指定 https://web.dev 來源。

如要在 JavaScript 中執行相同動作,請使用 CrUXApiUtil 公用程式 ,系統就會發出 API 呼叫並傳回已解碼的回應 (另請參閱 GitHub 變化版本 (包括記錄和批次支援) 更多功能)。

const CrUXApiUtil = {};
// Get your CrUX API key at https://goo.gle/crux-api-key.
CrUXApiUtil.API_KEY = '[YOUR_API_KEY]';
CrUXApiUtil.API_ENDPOINT = `https://chromeuxreport.googleapis.com/v1/records:queryRecord?key=${CrUXApiUtil.API_KEY}`;
CrUXApiUtil.query = function (requestBody) {
  if (CrUXApiUtil.API_KEY == '[YOUR_API_KEY]') {
    throw 'Replace "YOUR_API_KEY" with your private CrUX API key. Get a key at https://goo.gle/crux-api-key.';
  }
  return fetch(CrUXApiUtil.API_ENDPOINT, {
    method: 'POST',
    body: JSON.stringify(requestBody)
  }).then(response => response.json()).then(response => {
    if (response.error) {
      return Promise.reject(response);
    }
    return response;
  });
};

[YOUR_API_KEY] 替換成您的金鑰。接下來,呼叫 CrUXApiUtil.query 函式並傳入「要求主體」物件。

CrUXApiUtil.query({
  origin: 'https://web.dev'
}).then(response => {
  console.log(response);
}).catch(response => {
  console.error(response);
});

如果這個來源有資料,API 回應會是 JSON 編碼的物件,內含代表使用者體驗分佈情形的指標。分佈指標是直方圖特徵分塊和百分位數。

{
  "record": {
    "key": {
      "origin": "https://web.dev"
    },
    "metrics": {
      "largest_contentful_paint": {
        "histogram": [
          {
            "start": 0,
            "end": 2500,
            "density": 0.7925068547983514
          },
          {
            "start": 2500,
            "end": 4000,
            "density": 0.1317422195536863
          },
          {
            "start": 4000,
            "density": 0.07575092564795324
          }
        ],
        "percentiles": {
          "p75": 2216
        }
      },
      // ...
    }
  }
}

histogram 物件的 startend 屬性代表使用者在指定指標中經歷的值範圍。density 屬性代表該範圍內使用者體驗的比例。以這個範例來說,所有 web.dev 網頁的 LCP 使用者體驗中,有 79% 的使用者體驗低於 2,500 毫秒,成為「良好」LCP 門檻。percentiles.p75 值代表此分佈百分比中的 75% 使用者體驗低於 2,216 毫秒。如要進一步瞭解回應結構,請參閱回應主體說明文件。

錯誤

如果 CrUX API 沒有任何特定來源的資料,就會傳回 JSON 編碼的錯誤訊息:

{
  "error": {
    "code": 404,
    "message": "chrome ux report data not found",
    "status": "NOT_FOUND"
  }
}

如要對這個錯誤進行偵錯,請先檢查要求的來源是否可公開瀏覽。如要進行測試,請在瀏覽器的網址列中輸入來源,並與重新導向後的最終到達網址進行比較。常見問題包括不必要的新增或省略子網域,以及使用錯誤的 HTTP 通訊協定。

錯誤
{"origin": "http://www.web.dev"}

這個來源錯誤包含 http:// 通訊協定和 www. 子網域。

成功
{"origin": "https://web.dev"}

這個來源可公開瀏覽。

如果要求的來源「是」可瀏覽的版本,如果來源的樣本數量不足,也可能會發生這個錯誤。資料集內含的所有來源和網址都必須有足夠數量的樣本,才能匿名處理個別使用者。此外,來源和網址必須可公開建立索引。如要進一步瞭解網站納入資料集的方式,請參閱 CrUX 方法

查詢網址資料

您已瞭解如何查詢 CrUX API,瞭解特定來源的整體使用者體驗。如要將結果限制在特定頁面,請使用 url 要求參數。

API_KEY="[YOUR_API_KEY]"
curl "https://chromeuxreport.googleapis.com/v1/records:queryRecord?key=$API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{"url": "https://web.dev/fast/"}'

以下 cURL 指令與來源範例類似,差別在於要求主體使用 url 參數指定要查詢的網頁。

如要透過 JavaScript 查詢 CrUX API 的網址資料,請在要求主體中使用 url 參數呼叫 CrUXApiUtil.query 函式。

CrUXApiUtil.query({
  url: 'https://web.dev/fast/'
}).then(response => {
  console.log(response);
}).catch(response => {
  console.error(response);
});

如果 CrUX 資料集中存在這個網址的資料,API 就會傳回 JSON 編碼的回應。範例說明

{
  "record": {
    "key": {
      "url": "https://web.dev/fast/"
    },
    "metrics": {
      "largest_contentful_paint": {
        "histogram": [
          {
            "start": 0,
            "end": 2500,
            "density": 0.8477304539092148
          },
          {
            "start": 2500,
            "end": 4000,
            "density": 0.08988202359528057
          },
          {
            "start": 4000,
            "density": 0.062387522495501155
          }
        ],
        "percentiles": {
          "p75": 1947
        }
      },
      // ...
    }
  }
}

是,結果顯示「https://web.dev/fast/」有 85%「良好」LCP 體驗和第 75 個百分位數 (1,947 毫秒) 比全來源分佈略高。

網址正規化

CrUX API 可能會將要求的網址正規化,使其更貼近已知網址的清單。舉例來說,由於系統需經過正規化處理,因此查詢網址 https://web.dev/fast/#measure-performance-in-the-field 時,系統便會產生 https://web.dev/fast/ 的資料。發生這種情況時,回應中會包含 urlNormalizationDetails 物件。

{
  "record": {
    "key": {
      "url": "https://web.dev/fast/"
    },
    "metrics": { ... }
  },
  "urlNormalizationDetails": {
    "normalizedUrl": "https://web.dev/fast/",
    "originalUrl": "https://web.dev/fast/#measure-performance-in-the-field"
  }
}

如要進一步瞭解網址正規化,請參閱 CrUX 說明文件。

依板型規格查詢

使用者體驗可能會因網站最佳化、網路狀況和使用者裝置。如要進一步瞭解這些差異,請使用 CrUX API 的 formFactor 維度細查來源和網址成效。

API 支援三種明確的板型規格值:DESKTOPPHONETABLET。除了來源或網址外,您也可以在要求主體中指定其中一個值,將結果限制為只顯示這些使用者體驗。這個範例說明如何使用 cURL 依據板型規格查詢 API。

API_KEY="[YOUR_API_KEY]"
curl "https://chromeuxreport.googleapis.com/v1/records:queryRecord?key=$API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{"url": "https://web.dev/fast/", "formFactor": "PHONE"}'

如要使用 JavaScript 查詢 CrUX API 的板型規格專屬資料,請使用要求主體中的 urlformFactor 參數呼叫 CrUXApiUtil.query 函式。

CrUXApiUtil.query({
  url: 'https://web.dev/fast/',
  formFactor: 'PHONE'
}).then(response => {
  console.log(response);
}).catch(response => {
  console.error(response);
});

省略 formFactor 參數就等於要求所有板型規格組合的資料。

{
  "record": {
    "key": {
      "url": "https://web.dev/fast/",
      "formFactor": "PHONE"
    },
    "metrics": {
      "largest_contentful_paint": {
        "histogram": [
          {
            "start": 0,
            "end": 2500,
            "density": 0.778631284916204
          },
          {
            "start": 2500,
            "end": 4000,
            "density": 0.13943202979515887
          },
          {
            "start": 4000,
            "density": 0.08193668528864119
          }
        ],
        "percentiles": {
          "p75": 2366
        }
      },
    // ...
    }
  }
}

回應的 key 欄位會回應 formFactor 要求設定,確認只包含手機體驗。

上一節提到,85% 的使用者體驗「良好」LCP。相較於手機專屬的體驗,只有 78% 算是「良好」。相較之下,第 75 個百分位數同樣較慢,比 1,947 毫秒縮短到 2,366 毫秒。依據板型規格進行區隔,可能會使使用者體驗更加明顯差異。

評估 Core Web Vitals 效能

Core Web Vitals 計畫會定義目標,協助判定使用者體驗或體驗分佈情形是否可視為「良好」。在以下範例中,我們使用 CrUX API 和 CrUXApiUtil.query 函式評估網頁在 Core Web Vitals 指標 (LCP、FID、CLS) 的分佈情形是否「良好」。

CrUXApiUtil.query({
  url: 'https://web.dev/fast/'
}).then(response => {
  assessCoreWebVitals(response);
}).catch(response => {
  console.error(response);
});

function assessCoreWebVitals(response) {
  // See https://web.dev/vitals/#core-web-vitals.
  const CORE_WEB_VITALS = [
    'largest_contentful_paint',
    'first_input_delay',
    'cumulative_layout_shift'
  ];
  CORE_WEB_VITALS.forEach(metric => {
    const data = response.record.metrics[metric];
    if (!data) {
      console.log('No data for', metric);
      return;
    }
    const p75 = data.percentiles.p75;
    const threshold = data.histogram[0].end;
    // A Core Web Vitals metric passes the assessment if
    // its 75th percentile is under the "good" threshold.
    const passes = p75 < threshold;
    console.log(`The 75th percentile (${p75}) of ${metric} ` +
        `${passes ? 'passes' : 'does not pass'} ` +
        `the Core Web Vitals "good" threshold (${threshold}).`)
  });
}
敬上

結果顯示這個網頁通過了全部三項指標的 Core Web Vitals 評估。

The 75th percentile (1973) of largest_contentful_paint passes the Core Web Vitals "good" threshold (2500).
The 75th percentile (20) of first_input_delay passes the Core Web Vitals "good" threshold (100).
The 75th percentile (0.05) of cumulative_layout_shift passes the Core Web Vitals "good" threshold (0.10).

結合 CrUX 的資料,再加上自動監控 API 結果的功能,可確保真正的使用者體驗能快速取得保持快速流暢。如要進一步瞭解 Core Web Vitals 和評估方式,請參閱網站體驗指標評估 Core Web Vitals 的工具

後續步驟

初始版本的 CrUX API 提供的功能,只是 CrUX 能提供的洞察資訊。BigQuery 的 CrUX 資料集使用者可能對部分進階功能相當熟悉,包括:

  • 其他指標
    • first_paint
    • dom_content_loaded
    • onload
    • time_to_first_byte
    • notification_permissions
  • 其他維度
    • month
    • country
    • effective connection type (ECT)
  • 其他精細程度
    • 詳細的直方圖
    • 更多百分位數

查看官方的 CrUX API 文件,瞭解如何取得 API 金鑰,並瀏覽更多應用程式範例。希望您能抽空試用,如有任何疑問或意見回饋,歡迎透過 CrUX 論壇與我們聯絡。如要即時掌握我們規劃的 CrUX API 計畫,歡迎訂閱 CrUX 公告論壇,或是在 Twitter 上追蹤我們 (@ChromeUXReport)。