如何通过 Google Tag Manager for Next-Js 设置 Google Analytics? [英] How to set up Google Analytics through Google Tag Manager for Next-Js?

查看:12
本文介绍了如何通过 Google Tag Manager for Next-Js 设置 Google Analytics?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前我使用 react-ga npm 模块在我的下一个 js 应用程序中插入谷歌分析.就像这样:

formerly I was using react-ga npm module to insert google analytics in my next js app. and It was simply like this:

import ReactGA from 'react-ga'

export const initGA = () => {
  ReactGA.initialize('UA-*******-*', {
    titleCase: false
  })
}

export const logPageView = () => {
  if (window.location.href.split('?')[1]) {
    ReactGA.set({page: window.location.pathname + '?' + window.location.href.split('?')[1]})
    ReactGA.pageview(window.location.pathname + '?' + window.location.href.split('?')[1])
  } else {
    ReactGA.set({page: window.location.pathname})
    ReactGA.pageview(window.location.pathname)
  }
}

然后我在我的标题中调用 logPageView 函数(插入到我的应用程序的每个页面),如下所示:

and then I was calling logPageView function in my header(that was inserted to every page of my app) like this:

  componentDidMount () {
    if (!window.GA_INITIALIZED) {
      initGA()
      window.GA_INITIALIZED = true
    }
    logPageView()
  }
  componentWillReceiveProps () {
    if (!window.GA_INITIALIZED) {
      initGA()
      window.GA_INITIALIZED = true
    }
    logPageView()
  }

现在我想使用 Google Tag Manager 来处理分析页面视图.我怎么能这样做?

now I want to use Google Tag Manager to handle Analytics page view . How could I do this?

推荐答案

为了使用谷歌标签管理器,你应该在每个页面上注入你的标签管理器脚本.由于 _document.js 是每个页面的包装器,您应该将 GTM 脚本添加到 head 部分的 _document.js 中,如下所示:

In order to use Google Tag Manager you should inject your tag manager script on every page. since _document.js is the wrapper for every page, you should add the GTM script to _document.js in the head section like this:

<Head>
  <script dangerouslySetInnerHTML={{
    __html: `(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-*****');`,
  }}>
  </script>
  ...
</Head>

现在您已准备好在 next-js 应用中使用 Google 跟踪代码管理器.您应该只继续从您的 GTM 仪表板处理综合浏览量和其他与分析相关的内容.

Now you are all set to use Google Tag Manager in your next-js app. You should only proceed to handle pageview and other analytics related stuff from your GTM dashboard.

要为单页应用程序(如 nextjs)设置谷歌分析页面浏览,您可以按照 这些 步骤.

To set up google analytics pageview for single page applications(like nextjs) you can follow these steps.

这篇关于如何通过 Google Tag Manager for Next-Js 设置 Google Analytics?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆