如何使用到达路由器和谷歌分析跟踪页面浏览量?

And*_*nga 2 google-analytics reactjs create-react-app reach-router

我正在将主干应用程序移植到 React 应用程序。在主干应用程序中,我有以下代码段

    <!-- Begin UA code -->
    <script>
    window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
    ga('create', 'UA-xxx', 'auto');

    // Load plugins

    // Rewrite all GA pages with /ra_minisite prefix
    ga('require', 'cleanUrlTracker', {
      stripQuery: true,
      queryDimensionIndex: 1,
      urlFieldsFilter: function(fieldsObj, parseUrl) {
        fieldsObj.page = '/ra_minisite'+parseUrl(fieldsObj.page).pathname
        return fieldsObj;
      },
    });

    ga('require', 'eventTracker');
    ga('require', 'maxScrollTracker');

    // Customize so WS.com not tracked as outbound link
    ga('require', 'outboundLinkTracker');

    ga('require', 'socialWidgetTracker');
    ga('require', 'urlChangeTracker');

    // Commented out so we can call after all API calls are done
    // Called from metaManager
    // ga('send', 'pageview');

    </script>
    <script async src="https://www.google-analytics.com/analytics.js"></script>
    <script async src="/autotrack.js"></script>
    <!-- end UA code -->
Run Code Online (Sandbox Code Playgroud)

然后在更新它调用的元标记后在每个页面上呈现

window.ga('send', 'pageview');
Run Code Online (Sandbox Code Playgroud)

我假设我可以将 init 逻辑放到 index.html 中,但是有什么好的、简单的方法可以连接window.ga('send', 'pageview');到到达路由器,以便在路由更改或更新时,页面视图将发送到 GA?

Her*_*III 7

您可以收听全局历史对象。在您的App.js

import { globalHistory } from '@reach/router';

globalHistory.listen(({ location }) => {
  window.ga('send', 'pageview');
  // or use the new gtag API
  window.gtag('config', 'GA_MEASUREMENT_ID', {'page_path': location.pathname});
});
Run Code Online (Sandbox Code Playgroud)

这是最简单的方法,代码量最少,并且与LocationProvider顶部答案中提供的方法不同,它不会破坏全局navigateAPI。

不幸的是,它似乎globalHistory在任何地方都没有记录,所以很难找到。