如何为 React-Router 设置 Google Analytics 4?
How to set up Google Analytics 4 for React-Router?
我正在尝试在我的 React 站点上设置 Google Analytics 4。以前我用过react-ga,但是这个库还不支持Google Analytics 4。我直接把GA4标签粘贴到index.html文件中,没有外部库。我需要添加什么额外的代码才能让 GA4 与 React 路由器一起工作?
提前致谢!
您可以直接调用gtag
。只需将全局站点代码放入 index.html <head>
.
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>
我今天遇到了同样的问题,最后拔出了 react-ga 包并走这条路。我从 react-ga 演示代码中保存了 withTracker.js 部分,并按如下方式对其进行了修改。
export default function withTracker(WrappedComponent, options = {}) {
const trackPage = (page) => {
window.gtag('send', 'page_view', {
page_location: window.location.href,
page_path: window.location.pathname
});
};
...
您还可以签出 npm 包 ga-4-react:
不需要额外的代码,只需将该标签粘贴到 index.html 中,Google Analytics 就会跟踪您的所有网址。
您应该可以停止使用 react-ga,只需像 Cameron 提到的那样在 index.html 中插入全局脚本标签。请记住,您可能需要确保您的应用正在根据需要更新 window.location 和 document.title 用于 GA4 工作。
"When a pageview is sent to Analytics, the default page parameter values are used, unless modified. This means you do not need to modify page_title or page_location parameters if updates to window.location (e.g. via the History API) and document.title are made prior to the event being sent.".
我有一个简单的单页应用程序,在每次呈现时更新标题和位置之前,我没有收到详细的页面视图数据。
我正在尝试在我的 React 站点上设置 Google Analytics 4。以前我用过react-ga,但是这个库还不支持Google Analytics 4。我直接把GA4标签粘贴到index.html文件中,没有外部库。我需要添加什么额外的代码才能让 GA4 与 React 路由器一起工作?
提前致谢!
您可以直接调用gtag
。只需将全局站点代码放入 index.html <head>
.
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>
我今天遇到了同样的问题,最后拔出了 react-ga 包并走这条路。我从 react-ga 演示代码中保存了 withTracker.js 部分,并按如下方式对其进行了修改。
export default function withTracker(WrappedComponent, options = {}) {
const trackPage = (page) => {
window.gtag('send', 'page_view', {
page_location: window.location.href,
page_path: window.location.pathname
});
};
...
您还可以签出 npm 包 ga-4-react:
不需要额外的代码,只需将该标签粘贴到 index.html 中,Google Analytics 就会跟踪您的所有网址。
您应该可以停止使用 react-ga,只需像 Cameron 提到的那样在 index.html 中插入全局脚本标签。请记住,您可能需要确保您的应用正在根据需要更新 window.location 和 document.title 用于 GA4 工作。
"When a pageview is sent to Analytics, the default page parameter values are used, unless modified. This means you do not need to modify page_title or page_location parameters if updates to window.location (e.g. via the History API) and document.title are made prior to the event being sent.".
我有一个简单的单页应用程序,在每次呈现时更新标题和位置之前,我没有收到详细的页面视图数据。