放置 gtag 事件代码段标题 Gatsby/React 网站

place gtag event snippet head Gatsby/React site

我在将事件片段放入感谢 you-page 时遇到问题。该网站是用 GatsbyJS 构建的。我的想法是将事件片段放在使用 React 头盔中,但似乎无法弄清楚如何正确地做到这一点。我尝试了所有不同的方法,但似乎都不起作用:

<Helmet>
<script>
  gtag('event', 'conversion', {'send_to': 'AW-MYID'});
</script>
</Helmet>
<Helmet>
<script
  gtag('event', 'conversion', {'send_to': 'AW-MYID'});
/>
</Helmet>
<Helmet>
<script>
{`
  gtag('event', 'conversion', {'send_to': 'AW-MYID'});
`}
</script>
</Helmet>

根据 gatsby-plugin-google-gtag 文档在 server-side 渲染 (SSR) 中添加自定义事件:

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

您需要先访问 window 对象。当然,在检查是否可用后,请求时间为 debugging HTML in Gatsby shows.

当然,这假设您已经在 gatsby-config.js 中正确安装了插件。理想的定制应如下所示:

  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/"],
        },
      },
    },
  ],