【问题标题】:How to properly use Google Tag script in Next.js?如何在 Next.js 中正确使用 Google Tag 脚本?
【发布时间】:2022-01-09 17:03:41
【问题描述】:

我读过How to load Google Tag Manager with next/script component (Next.js 11)?,也读过this doc page

但他们都没有解决我的问题。

我想在我使用 nextjs 开发的许多网站上包含 Google 标记。因此,我创建了一个简单的可重用组件:

import Script from 'next/script'

const GoogleTag = ({ identifier }) => {
    if (!identifier || !identifier.startsWith('G-')) {
        throw new Error('Google tag id is not correct;');
    }
    return <>
        <Script
            src={`https://www.googletagmanager.com/gtag/js?id=${identifier}`}
            strategy="afterInteractive"
        />
        <Script id="google-analytics" strategy="afterInteractive">
            {`
          window.dataLayer = window.dataLayer || [];
          function gtag(){window.dataLayer.push(arguments);}
          gtag('js', new Date());

          gtag('config', '${identifier}');
        `}
        </Script>
    </>
}

export default GoogleTag;

我在我的每个站点中使用它,在 _app.js 文件中,这样:

import Head from 'next/head';
import GoogleTag from '../Base/GoogleTag';

export default function MyApp({ Component, pageProps }) {

return (
        <>
            <Head>
                <GoogleTag identifier='G-9XLT855ZE0' />
            </Head>
            <div>
                application code comes here
            </div>
        </>
    )
}

但我没有看到在 Chrom 的开发工具的 int Networks 选项卡中加载了 Google Tag 脚本。

【问题讨论】:

标签: javascript next.js


【解决方案1】:

要在您的next.js 应用程序中正确使用google tag,您应该在Head 部分中将GTM 脚本添加到_document.js

示例代码_documents.jssource.

import Document, { Html, Head, Main, NextScript } from 'next/document'

import { GA_TRACKING_ID } from '../lib/gtag'

export default class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head>
          {/* Global Site Tag (gtag.js) - Google Analytics */}
          <script
            async
            src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
          />
          <script
            dangerouslySetInnerHTML={{
              __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${GA_TRACKING_ID}', {
              page_path: window.location.pathname,
            });
          `,
            }}
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

为单页应用设置谷歌分析页面视图,以及在 next.js 中使用 GT 的其他方法。你可以访问这个source1source2

【讨论】:

  • &lt;Head&gt;组件来看_app.js_document.js有什么区别?他们不是一样的吗?
  • @HosseinFallah 不,他们不一样! stackoverflow.com/questions/51040669/… 。试试我发给你的方法,用这个例子作为文档,我检查了一下,它可以工作。祝你好运和最好的问候!
猜你喜欢
  • 2021-10-05
  • 1970-01-01
  • 2020-08-30
  • 2013-10-13
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多