如何使用 CrUX API

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

Shane Exterkamp
Shane Exterkamp

Chrome 使用者體驗報告 (CrUX) 資料集代表 Chrome 使用者實際造訪熱門網址的情形。自 2017 年在 BigQuery 上首次發布可查詢的資料集以來,CrUX 的現場資料已整合至 PageSpeed Insights 等開發人員工具,以及 Search Console 的 Core Web Vitals 報告,方便開發人員評估及監控實際使用者體驗。一直以來,我們缺少的是一種工具,可透過程式輔助方式,免費且以 RESTful 形式存取 CrUX 資料。為協助縮小這項差距,我們很高興宣布推出全新的 Chrome 使用者體驗報告 API

這項 API 的目標是讓開發人員快速且全面地存取 CrUX 資料。與現有的 PageSpeed Insights API 不同,CrUX API 只會回報現場使用者體驗資料,而後者還會回報 Lighthouse 效能稽核的實驗室資料。CrUX API 經過簡化,可快速提供使用者體驗資料,非常適合用於即時稽核應用程式。

為確保開發人員能存取最重要的指標 (即 Core Web Vitals),CrUX API 會稽核及監控來源和網址層級的 Largest Contentful Paint (LCP)、Interaction to Next Paint (INP) 和 Cumulative Layout Shift (CLS)。

現在就來深入瞭解如何使用這項功能!

在本頁面試用 API

試試看!

查詢原始資料

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 說明文件

依板型規格查詢

使用者體驗可能因網站最佳化、網路狀況和使用者裝置而有顯著差異。如要進一步瞭解這些差異,請使用 Chrome 使用者體驗報告 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 毫秒。按外型規格區隔,可突顯使用者體驗的極端差異。

評估網站體驗核心指標成效

網站使用體驗核心指標計畫定義了目標,有助於判斷使用者體驗或體驗分布是否可視為「良好」。在下列範例中,我們會使用 CrUX API 和 CrUXApiUtil.query 函式,評估網頁的 Core Web Vitals 指標 (LCP、INP、CLS) 分布是否「良好」。

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

function assessCoreWebVitals(response) {
  // See https://web.dev/articles/vitals/#core-web-vitals.
  const CORE_WEB_VITALS = [
    'largest_contentful_paint',
    'interaction_to_next_paint',
    '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}).`)
  });
}

結果顯示,這個網頁通過了所有三項指標的網站體驗核心指標評量。

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

搭配自動監控 API 結果的方式,即可使用 CrUX 的資料,確保實際使用者體驗快速維持快速。如要進一步瞭解 Core Web Vitals 和評估方式,請參閱「網站體驗核心指標」和「評估網站體驗核心指標的工具」。

後續步驟

CrUX API 初始版本的功能僅能提供 CrUX 洞察資料的初步資訊。BigQuery 上的 CrUX 資料集使用者可能熟悉一些進階功能,包括:

  • 其他指標
    • first_paint
    • dom_content_loaded
    • onload
    • time_to_first_byte
    • notification_permissions
  • 其他維度
    • month
    • country
  • 其他精細程度
    • 詳細直方圖
    • 更多百分位數

請參閱官方 CrUX API 說明文件,瞭解如何取得 API 金鑰,並查看更多範例應用程式。希望您會試用這項功能,並在 CrUX 討論論壇上提出任何問題或意見回饋。如要掌握 CrUX API 的最新消息,請訂閱 CrUX 公告論壇,或在 Twitter 上追蹤 @ChromeUXReport