javascript 在 React for Google Analytics 中安装 Google Tag Manager 有困难
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51996438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difficulty installing Google Tag Manager in React for Google Analytics
提问by Dog
I am trying to install Google Tag Manager on my React site, but when I read the documentation for Google Tag Manager it indicates that I should paste a long script tag into the head and body of every page:
我正在尝试在我的 React 站点上安装 Google 标签管理器,但是当我阅读 Google 标签管理器的文档时,它表明我应该将一个长脚本标签粘贴到每个页面的头部和正文中:
<!-- Google Tag Manager -->
<script>(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-XXXX');</script>
<!-- End Google Tag Manager -->
However, React sites do not traditionally use the script tag. How can I effectively and efficiently set my React site up with Google Tag Manager? Are there special React or JavaScript tags for SPAs?
然而,React 站点传统上不使用脚本标签。如何使用 Google Tag Manager 有效且高效地设置我的 React 站点?SPA 是否有特殊的 React 或 JavaScript 标签?
回答by Paul Makhnovskiy
You can add that script in /public/index.html since its a single page app but will only load once unless you add events depending on what your Google Tags do.
您可以在 /public/index.html 中添加该脚本,因为它是一个单页应用程序,但只会加载一次,除非您根据您的 Google 标签的功能添加事件。
To implement Google Tag Manager, use NPM package for more customizable options: https://www.npmjs.com/package/react-google-tag-manager
要实现 Google 标签管理器,请使用 NPM 包以获得更多可定制的选项:https: //www.npmjs.com/package/react-google-tag-manager
If you're using Google analytics within your tag manger, read below.
如果您在标签管理器中使用 Google 分析,请阅读以下内容。
Best approach is to use Google Analytics React NPM Package: https://github.com/react-ga/react-ga
最好的方法是使用 Google Analytics React NPM 包:https: //github.com/react-ga/react-ga
Add: ReactGA.pageview(window.location.pathname + window.location.search);in your router change to make sure you get your page hits.
添加:ReactGA.pageview(window.location.pathname + window.location.search);在您的路由器中更改以确保您获得页面点击量。

