以前我使用react-ga npm 模块在我的下一个js 应用程序中插入谷歌分析。就是这样:
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 函数(已插入到我的应用程序的每个页面中),如下所示:
componentDidMount () {
if (!window.GA_INITIALIZED) {
initGA()
window.GA_INITIALIZED = true
}
logPageView()
}
componentWillReceiveProps () {
if (!window.GA_INITIALIZED) {
initGA()
window.GA_INITIALIZED = true
}
logPageView()
}
现在我想使用Google Tag Manager来处理Analytics页面视图。我怎么能这样做呢?
为了使用 Google 跟踪代码管理器,您应该在每个页面上注入跟踪代码管理器脚本。自从_document.js
是每个页面的包装器,您应该将 GTM 脚本添加到_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>
现在您已准备好在 next-js 应用程序中使用 Google 跟踪代码管理器。您应该只继续从 GTM 仪表板处理页面浏览量和其他与分析相关的内容。
要为单页应用程序(如 nextjs)设置谷歌分析页面视图,您可以按照these http://tech.webinterpret.com/how-to-make-google-analytics-work-in-a-single-page-application-spa/#abetterway steps.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)