如何为 React-Router 设置 Google Analytics 4?

Spo*_*aPh 9 google-analytics reactjs react-router

我正在尝试在我的 React 站点上设置 Google Analytics 4。以前我使用过 react-ga,但是这个库还不支持 Google Analytics 4。我将 GA4 标签直接粘贴到 index.html 文件中,没有外部库。我需要添加哪些额外的代码才能让 GA4 与 React 路由器一起工作?
提前致谢!

cam*_*rch 8

可以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>
Run Code Online (Sandbox Code Playgroud)

我今天面临同样的问题,最终拉出 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            
        });
    };
...
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

2626 次

最近记录:

4 年,6 月 前