使用 Google Analytics(分析)4

本教程演示了如何使用 Google Analytics(分析)跟踪扩展程序的使用情况。您可以在 GitHub 上找到有效的 Google Analytics(分析)4 示例,其中的 google-analytics.js 包含所有与 Google Analytics(分析)相关的代码。

要求

本教程假定您熟悉编写 Chrome 扩展程序的方法。如果您需要有关如何编写扩展程序的信息,请参阅入门教程

您还必须设置一个 Google Analytics(分析)4 帐号来跟踪您的附加信息。请注意,在设置帐号时,您可以使用“网站网址”字段中的任意值,因为您的附加信息没有自己的网址。

使用 Google Analytics(分析)Measurement Protocol

自 Manifest V3 开始,Chrome 扩展程序无法执行远程托管的代码。这意味着您必须使用 Google Analytics(分析)Measurement Protocol 来跟踪扩展程序事件。借助 Measurement Protocol,您可以通过 HTTP 请求直接将事件发送到 Google Analytics(分析)服务器。这种方法的一个好处是,它允许您从扩展程序中的任何位置(包括 Service Worker)发送分析事件。

设置 API 凭据

第一步是获取 api_secretmeasurement_id。请参阅 Measurement Protocol 文档,了解如何为您的 Google Analytics(分析)帐号获取这些信息。

生成 client_id

第二步是为特定设备/用户生成唯一标识符 (client_id)。只要用户的浏览器中安装了该扩展程序,该 ID 就应保持不变。它可以是任意字符串,但对客户端而言应该是唯一的。您可以通过调用 self.crypto.randomUUID() 生成一个。将 client_id 存储在 chrome.storage.local 中,确保该扩展程序在安装期间保持不变。

要使用 chrome.storage.local,您需要清单文件中的 storage 权限:

manifest.json:

{
  …
  "permissions": ["storage"],
  …
}

然后,您可以使用 chrome.storage.local 存储 client_id

async function getOrCreateClientId() {
  const result = await chrome.storage.local.get('clientId');
  let clientId = result.clientId;
  if (!clientId) {
    // Generate a unique client ID, the actual value is not relevant
    clientId = self.crypto.randomUUID();
    await chrome.storage.local.set({clientId});
  }
  return clientId;
}

发送分析事件

利用 API 凭据和 client_id,您可以通过 fetch 请求向 Google Analytics(分析)发送事件:

const GA_ENDPOINT = 'https://www.google-analytics.com/mp/collect';
const MEASUREMENT_ID = `G-...`;
const API_SECRET = `...`;

fetch(
  `${GA_ENDPOINT}?measurement_id=${MEASUREMENT_ID}&api_secret=${API_SECRET}`,
  {
    method: 'POST',
    body: JSON.stringify({
      client_id: await getOrCreateClientId(),
      events: [
        {
          name: 'button_clicked',
          params: {
            id: 'my-button',
          },
        },
      ],
    }),
  }
);

这会发送一个 button_clicked 事件,该事件会显示在您的 Google Analytics(分析)事件报告中。如果您希望在 Google Analytics(分析)实时报告中查看事件,则需要另外提供两个参数:session_idengagement_time_msec

使用推荐参数 session_idengagement_time_msec

session_idengagement_time_msec 都是使用 Google Analytics(分析)Measurement Protocol 时的推荐参数,因为它们是显示在“实时”等标准报告中的用户活动所必需的参数。

session_id 描述了一段时间,用户在这段时间内会持续与您的扩展程序互动。默认情况下,会话会在用户处于不活动状态 30 分钟后结束。会话无持续时间限制。

与普通网站不同,在 Chrome 扩展程序中,没有明确的用户会话概念。因此,您必须在扩展程序中定义用户会话的含义。例如,每次新的用户互动都可能是一个新会话。在这种情况下,您可以直接为每个事件生成新的会话 ID(即使用时间戳)。

以下示例演示了一种方法,该方法会在未报告任何事件 30 分钟后让新会话超时(该时间可以自定义,以更好地适应扩展程序的用户行为)。该示例使用 chrome.storage.session 在浏览器运行时存储活动会话。我们与会话一起存储上次触发事件的时间。通过这种方式,我们可以判断活动会话是否已过期:

const SESSION_EXPIRATION_IN_MIN = 30;

async function getOrCreateSessionId() {
  // Store session in memory storage
  let {sessionData} = await chrome.storage.session.get('sessionData');
  // Check if session exists and is still valid
  const currentTimeInMs = Date.now();
  if (sessionData && sessionData.timestamp) {
    // Calculate how long ago the session was last updated
    const durationInMin = (currentTimeInMs - sessionData.timestamp) / 60000;
    // Check if last update lays past the session expiration threshold
    if (durationInMin > SESSION_EXPIRATION_IN_MIN) {
      // Delete old session id to start a new session
      sessionData = null;
    } else {
      // Update timestamp to keep session alive
      sessionData.timestamp = currentTimeInMs;
      await chrome.storage.session.set({sessionData});
    }
  }
  if (!sessionData) {
    // Create and store a new session
    sessionData = {
      session_id: currentTimeInMs.toString(),
      timestamp: currentTimeInMs.toString(),
    };
    await chrome.storage.session.set({sessionData});
  }
  return sessionData.session_id;
}

以下示例将 session_idengagement_time_msec 添加到了上一个按钮点击事件请求中。对于 engagement_time_msec,您可以提供默认值 100 ms

const GA_ENDPOINT = "https://www.google-analytics.com/mp/collect";
const MEASUREMENT_ID = `G-...`;
const API_SECRET = `...`;
const DEFAULT_ENGAGEMENT_TIME_IN_MSEC = 100;

fetch(
`${GA_ENDPOINT}?measurement_id=${MEASUREMENT_ID}&api_secret=${API_SECRET}`,
  {
    method: "POST",
    body: JSON.stringify({
      client_id: await getOrCreateClientId(),
      events: [
        {
          name: "button_clicked",
          params: {
            session_id: await this.getOrCreateSessionId(),
            engagement_time_msec: DEFAULT_ENGAGEMENT_TIME_IN_MSEC,
            id: "my-button",
          },
        },
      ],
    }),
  }
);

此事件在 Google Analytics(分析)“实时”报告中将按如下方式显示。

Google Analytics(分析)中的实时事件。

跟踪弹出式窗口、侧边栏和扩展程序页面中的网页浏览量

Google Analytics(分析)Measurement Protocol 支持特殊的 page_view 事件,可用于跟踪网页浏览量。使用此方法可在新标签页中跟踪访问您的弹出式页面、侧边栏或扩展程序页面的用户。page_view 事件还需要 page_titlepage_location 参数。以下示例针对扩展程序弹出式窗口在文档的 load 事件中触发网页浏览事件:

popup.js:

window.addEventListener("load", async () => {
  fetch(`${GA_ENDPOINT}?measurement_id=${MEASUREMENT_ID}&api_secret=${API_SECRET}`,
  {
    method: "POST",
    body: JSON.stringify({
      client_id: await getOrCreateClientId(),
      events: [
        {
          name: "page_view",
          params: {
            session_id: await getOrCreateSessionId(),
            engagement_time_msec: DEFAULT_ENGAGEMENT_TIME_IN_MSEC,
            page_title: document.title,
            page_location: document.location.href
          },
        },
      ],
    }),
  });
});

popup.js 脚本需要导入到弹出式窗口的 HTML 文件中,并且应在执行任何其他脚本之前运行:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Analytics Demo Popup</title>
    <script src="./popup.js" type="module"></script>
  </head>
  <body>
    <h1>Analytics Demo</h1>
  </body>
</html>

弹出式视图的显示方式与 Google Analytics(分析)实时报告中的任何其他网页浏览一样:

Google Analytics(分析)“实时”信息中心内显示的网页浏览事件。

跟踪 Service Worker 中的分析事件

使用 Google Analytics(分析)Measurement Protocol 可以跟踪扩展程序 Service Worker 中的分析事件。例如,通过监听 Service Worker 中的 unhandledrejection event,您可以将 Service Worker 中未捕获的任何异常记录到 Google Analytics(分析)中,这对于调试用户可能报告的问题非常有帮助。

service-worker.js

addEventListener("unhandledrejection", async (event) => {
  `${GA_ENDPOINT}?measurement_id=${MEASUREMENT_ID}&api_secret=${API_SECRET}`,
  {
    method: "POST",
    body: JSON.stringify({
      client_id: getOrCreateClientId(),
      events: [
        {
          // Note: 'error' is a reserved event name and cannot be used
          // see https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference?client_type=gtag#reserved_names
          name: "extension_error",
          params: {
            session_id: await this.getOrCreateSessionId(),
            engagement_time_msec: DEFAULT_ENGAGEMENT_TIME_IN_MSEC,
            message: error.message,
            stack: error.stack,
          },
        },
      ],
    }),
  }
});

现在,您可以在 Google Analytics(分析)报告中查看错误事件:

Google Analytics(分析)事件信息中心内显示的错误事件。

调试

Google Analytics(分析)提供了两项实用功能,用于将分析事件调试到扩展程序中:

  1. 特殊的调试端点 https://www.google-analytics.com**/debug**/mp/collect,用于报告事件定义中的任何错误。
  2. Google Analytics(分析)“实时”报告:将出现事件时显示这些事件。