如何通过适用于Next-J的Google跟踪代码管理器设置Google Analytics(分析)? [英] How to set up Google Analytics through Google Tag Manager for Next-Js?

查看:68
本文介绍了如何通过适用于Next-J的Google跟踪代码管理器设置Google Analytics(分析)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前,我曾经使用react-ga npm模块在我的下一个js应用程序中插入Google Analytics(分析).就像这样:

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跟踪代码管理器来处理Google Analytics(分析)页面视图.我该怎么办?

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

推荐答案

要使用Google跟踪代码管理器,您应该在每个页面上插入跟踪代码管理器脚本.由于 _document.js 是每个页面的包装,因此您应该将GTM脚本添加到 _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)设置Google Analytics(分析)浏览量,您可以按照

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

这篇关于如何通过适用于Next-J的Google跟踪代码管理器设置Google Analytics(分析)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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