首页 > 解决方案 > 放置 gtag 事件片段头 Gatsby/React 站点

问题描述

我在感谢页面上放置事件片段时遇到问题。该站点是用 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>

标签: javascriptreactjsgatsbygtag.jsreact-helmet

解决方案


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

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

您需要先访问window对象。当然,在检查它是否可用之后,如Gatsby 中的调试 HTML 显示的请求时间。

当然,这假设你已经在你的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/"],
        },
      },
    },
  ],

推荐阅读