如何在Next.js中正确使用Google Tag脚本



我阅读了如何加载带有next/script组件的Google Tag Manager(next.js 11(?我还看了这个文档页。

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

我想在我的许多使用nextjs开发的网站上加入谷歌标签。因此,我创建了一个简单的可重用组件:

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网络选项卡

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

示例代码_documents.js,源代码。

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的其他方法。您可以访问此source1、source2。

最新更新