如何通过适用于Next-J的Google跟踪代码管理器设置Google Analytics(分析)?

Soo*_*ena 4 google-tag-manager nextjs

以前我是使用react-ga npm模块在下一个js应用中插入Google Analytics(分析)。就像这样:

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)
  }
}
Run Code Online (Sandbox Code Playgroud)

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

  componentDidMount () {
    if (!window.GA_INITIALIZED) {
      initGA()
      window.GA_INITIALIZED = true
    }
    logPageView()
  }
  componentWillReceiveProps () {
    if (!window.GA_INITIALIZED) {
      initGA()
      window.GA_INITIALIZED = true
    }
    logPageView()
  }
Run Code Online (Sandbox Code Playgroud)

现在,我想使用Google跟踪代码管理器来处理Google Analytics(分析)页面视图。我该怎么办?

Bla*_*ack 23

不需要任何特殊的图书馆,这里的一些答案看起来不完整。只需在 _document.js 中添加脚本<Head>和 noscript<body>

import Head from 'next/document'  

<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-XXXXXX');`}} />
</Head>
    
<body style={{ margin: 0 }}>
   <noscript dangerouslySetInnerHTML={{ __html: `<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXX"
        height="0" width="0" style="display:none;visibility:hidden"></iframe>`,
      }}
    />
    <Main />
    <NextScript />
</body>
Run Code Online (Sandbox Code Playgroud)

  • 您可能想从“next/document”而不是“next/head”导入 Head 组件。即`从'next/document'导入{Head}`。根据 nextjs [文档](https://nextjs.org/docs/advanced-features/custom-document),它们并不相同,对于所有页面通用的代码,首选来自“next/document”的代码。 (3认同)

Soo*_*ena 14

为了使用Google跟踪代码管理器,您应该在每个页面上注入跟踪代码管理器脚本。因为_document.js是每个页面的包装器。您应该像这样在头部分的_document.js中插入标签管理器的脚本:

<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>
Run Code Online (Sandbox Code Playgroud)

现在,您都可以在next-js应用程序中使用google标记管理器了,您只应继续处理标记管理器仪表板中的综合浏览量和其他与分析相关的内容。

要为单页应用程序(如nextjs)设置Google Analytics(分析)综合浏览量,请按照以下步骤操作。

  • @MuhammadRiyaz 只要您确定脚本是安全的并且在这种情况下它是安全的,它就不危险 (3认同)
  • 如果有人设法操纵angerlySetInnerHTML 中的任何内容,那么您将遇到比谷歌分析更大的问题。 (2认同)

Sag*_*r M 10

我找到了一个更好的实现方式。我们可以使用react-gtm-module图书馆。

正如 Ryan Elinska 在他们的博客中提到的,我的 NextJS 安装文件中 Next.js中的Google 标签管理器_app.js

import App, { Container } from 'next/app'
import React from 'react'
import './app.css'
import TagManager from 'react-gtm'

const tagManagerArgs = {
  id: 'GTM-XXXXXXX'
}

class MyApp extends App {
  componentDidMount () {
    TagManager.initialize(tagManagerArgs)
  }

  render () {
    const { Component, pageProps } = this.props
    return (
      <Container>
        <Component {...pageProps} />
      </Container>
    )
  }
}

export default MyApp
Run Code Online (Sandbox Code Playgroud)


Dar*_*ert 7

由于您使用的是nextJS,因此无需从Google Analytics(分析)中添加纯JavaScript,您所需要做的就是GA跟踪ID。

然后创建util函数:

export const event = ({ action, category, label, value }) => {
  window.gtag('event', action, {
    event_category: category,
    event_label: label,
    value: value
  })
}
Run Code Online (Sandbox Code Playgroud)

并将其添加到您的_document.js中:

<script
  dangerouslySetInnerHTML={{
  __html: `
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', '${GA_TRACKING_ID}');
`}}
/>
Run Code Online (Sandbox Code Playgroud)

之后,您只需要在页面/组件中导入util函数并调用:

gtag.event({
  action: 'submit_form',
  category: 'Contact',
  label: this.state.message
})
Run Code Online (Sandbox Code Playgroud)

参考:带有GA的NextJS示例


小智 5

我在里面使用react-gtm-module和配置_app.jscomponentDidMount

 componentDidMount() {
    const tagManagerArgs = {
      gtmId = 'GTM-00001'
    }

    TagManager.initialize(tagManagerArgs);
  }
Run Code Online (Sandbox Code Playgroud)

这是我于 2020 年 2 月 11 日更新的解决方案