![](/img/trans.png)
[英]How to load Google Tag Manager with next/script component (Next.js 11)?
[英]How to properly use Google Tag script in Next.js?
我阅读了如何使用 next/script 组件(Next.js 11)加载 Google 跟踪代码管理器? 我还阅读了这个文档页面。
但他们都没有解决我的问题。
我想在我使用 nextjs 开发的许多网站上包含 Google Tag。 因此,我创建了一个简单的可重用组件:
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 脚本。
要在next.js
应用程序中正确使用google tag
,您应该将 GTM 脚本添加到Head
部分的_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 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.