how to use the Google Tag Manager plugin for gatsby?

淺唱寂寞╮ 提交于 2019-12-06 06:28:58

问题


Please note that I'm still learning to use Gatsby & React.

I have been trying to figure out how to properly use the Google Tag Manager Plugin for Gatsbyjs to insert tracking codes into my app.

The official documentation of the plugin does not provide a lot of insights and examples, so I'm not sure if I understand it completely.

What I want to do is to insert two GTM tracking codes into my app, one in <head> and one in <body>. With the static site approach, I could just copy and paste the GTM tracking codes into my HTML documents, however, with Gatsby & React, it does not work that way.

For example, I want to insert the following code to the <head>

<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXX');</script>
<!-- End Google Tag Manager -->

I open the gatsby-config.js file and paste the following under plugins

// In your gatsby-config.js
plugins: [
  {
    resolve: `gatsby-plugin-google-tagmanager`,
    options: {
      id: "YOUR_GOOGLE_TAGMANAGER_ID",

      // Include GTM in development.
      // Defaults to false meaning GTM will only be loaded in production.
      includeInDevelopment: false,

      // Specify optional GTM environment details.
      gtmAuth: "YOUR_GOOGLE_TAGMANAGER_ENVIROMENT_AUTH_STRING",
      gtmPreview: "YOUR_GOOGLE_TAGMANAGER_ENVIROMENT_PREVIEW_NAME",
    },
  },
]

It seems like the only thing I need to do here is replacing 'YOUR_GOOGLE_TAGMANAGER_ID' with my own GTM-ID. However, after I've done that and check the source code after the build, it shows

<script async="" src="https://www.googletagmanager.com/gtm.js?id=GTM-XXXXX;gtm_auth=YOUR_GOOGLE_TAGMANAGER_ENVIROMENT_AUTH_STRING&amp;gtm_preview=YOUR_GOOGLE_TAGMANAGER_ENVIROMENT_PREVIEW_NAME&amp;gtm_cookies_win=x"></script>

am I missing something here, Please help


回答1:


If you're going to be using the plugin mentioned in your question then you can just insert that plugin in gatsby-config.js file inside plugin property.

However, if you just want to plop the <script> tag that GTM provides you then you'd have to customize the html.js file of gatsby a little. Basically, it will let you put anything you'd like just like in any of your other html files.



来源:https://stackoverflow.com/questions/52883774/how-to-use-the-google-tag-manager-plugin-for-gatsby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!