立即迁移到 Netlify

Netlify 宣布 Gatsby Cloud 的下一次迭代。 了解更多

联系我们注册
官方插件
在 GitHub 上查看插件

gatsby-plugin-google-gtag

轻松为您的Gatsby网站添加Google Global Site Tag。

全局网站标签(gtag.js)是一个JavaScript标签框架和API,可让您将事件数据发送到Google Analytics,Google Ads,Campaign Manager,Display & Video 360和Search Ads 360。

全局网站标签(gtag.js)旨在结合多个Google标签系统,并可以取代旧的标签,例如analytics.jsgatsby-plugin-google-analytics)。

有关gtag的更多一般信息,您可以阅读Google的官方文档:https://developers.google.com/gtagjs/

如果您正在从analytics.js(gatsby-plugin-google-analytics)迁移,您可以更详细地阅读其中的细微API差异:https://developers.google.com/analytics/devguides/migration/ua/analyticsjs-to-gtagjs

请注意:此插件仅在生产模式下有效!要测试您的全局网站标签是否已正确安装并触发事件,请运行:gatsby build && gatsby serve.

安装

npm install gatsby-plugin-google-gtag

如何使用

此插件正常工作时,trackingIds选项是必需的。

gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-google-gtag`,
      options: {
        // You can add multiple tracking ids and a pageview event will be fired for all of them.
        trackingIds: [
          "GA-TRACKING_ID", // Google Analytics / GA
          "AW-CONVERSION_ID", // Google Ads / Adwords / AW
          "DC-FLOODIGHT_ID", // Marketing Platform advertising products (Display & Video 360, Search Ads 360, and Campaign Manager)
        ],
        // This object gets passed directly to the gtag config command
        // This config will be shared across all trackingIds
        gtagConfig: {
          optimize_id: "OPT_CONTAINER_ID",
          anonymize_ip: true,
          cookie_expires: 0,
        },
        // This object is used for configuration specific to this plugin
        pluginConfig: {
          // Puts tracking script in the head instead of the body
          head: false,
          // Setting this parameter is also optional
          respectDNT: true,
          // Avoids sending pageview hits from custom paths
          exclude: ["/preview/**", "/do-not-track/me/too/"],
          // Defaults to https://#
          origin: "YOUR_SELF_HOSTED_ORIGIN",
          // Delays processing pageview events on route update (in milliseconds)
          delayOnRouteUpdate: 0,
        },
      },
    },
  ],
}

gtagConfig.anonymize_ip选项

一些国家(例如德国)要求您为Google网站标签使用_anonymizeIP函数。否则,您将不允许使用它。该选项会添加下面的代码块

function gaOptout() {
  ;(document.cookie =
    disableStr + "=true; expires=Thu, 31 Dec 2099 23:59:59 UTC;path=/"),
    (window[disableStr] = !0)
}

var gaProperty = "UA-XXXXXXXX-X",
  disableStr = "ga-disable-" + gaProperty
document.cookie.indexOf(disableStr + "=true") > -1 && (window[disableStr] = !0)

如果您的访问者能够设置一个选择退出Cookie(未来不再跟踪),您可以例如在您的法律声明中设置一个链接,如下所示

<a href="javascript:gaOptout();">停用Google跟踪</a>

gtagConfig.optimize_id选项

如果您需要使用Google Optimize进行A/B测试,您可以添加此可选的Optimize容器ID,以允许Google Optimize加载您网站的正确测试参数。

其他gtagConfig选项

gtagConfig会直接传递给gtag config命令,因此您可以指定它支持的任何内容,例如gtagConfig.cookie_namegtagConfig.sample_rate。如果您正在从analytics.js插件迁移,这意味着所有“仅创建”字段都应使用下划线分隔(snake_cased)。

pluginConfig.respectDNT选项

如果启用此可选选项,则根本不会为启用了“请勿跟踪”的访问者加载Google Global Site Tag。虽然使用Google Global Site Tag不一定构成跟踪,但您可能仍希望这样做以迎合更多注重隐私的用户。

pluginConfig.exclude选项

如果您需要从跟踪系统中排除任何路径,您可以将其(一个或多个)添加为glob表达式到此可选数组中。

pluginConfig.delayOnRouteUpdate选项

如果您需要在路由更新时延迟处理页面浏览事件(例如,等待页面过渡,例如使用gatsby-plugin-transition-link),那么此选项将在生成页面浏览事件之前添加延迟。

自定义事件

此插件会在每次Gatsby路由更改时自动向所有指定为“trackingIds”的产品发送一个“pageview”事件。

如果您想调用自定义事件,您可以访问window.gtag,您可以在其中为所有产品调用一个事件

window.gtag("event", "click", { ...data })

或者您可以针对特定产品

window.gtag("event", "click", { send_to: "AW-CONVERSION_ID", ...data })

无论哪种情况,都不要忘记针对SSR进行保护

typeof window !== "undefined" && window.gtag("event", "click", { ...data })

为了方便跟踪出站链接上的点击,该插件提供了一个组件。

要使用它,只需导入它并像使用<a>元素一样使用它,例如

import React from "react"
import { OutboundLink } from "gatsby-plugin-google-gtag"

export default () => (
  <div>
    <OutboundLink href="https://gatsbyjs.com.cn/plugins/gatsby-plugin-google-gtag/">
      Visit the Google Global Site Tag plugin page!
    </OutboundLink>
  </div>
)
©2025Gatsby, Inc.