How to set up Google Analytics for React-Router?

后端 未结 15 651
名媛妹妹
名媛妹妹 2020-12-12 12:25

I\'m trying set up Google Analytics on my react site, and have come across a few packages, but none of which has the kind of set up that I have in terms of examples. Was ho

15条回答
  •  一向
    一向 (楼主)
    2020-12-12 13:21

    First, in your index.js set onUpdate function to call ga

    import ga from 'ga.js';
    onUpdate() {
      console.log('=====GA=====>', location.pathname);
      console.log('=====GA_TRACKING_CODE=====>', GA_TRACKING_CODE);
      ga("send", "pageview", location.pathname);
    }
    
    render() {
      return (
        ...
      );
    }
    

    And ga.js:

    'use strict';
    if(typeof window !== 'undefined' && typeof GA_TRACKING_CODE !== 'undefined') {
      (function(window, document, script, url, r, tag, firstScriptTag) {
        window['GoogleAnalyticsObject']=r;
        window[r] = window[r] || function() {
          (window[r].q = window[r].q || []).push(arguments)
        };
        window[r].l = 1*new Date();
        tag = document.createElement(script),
        firstScriptTag = document.getElementsByTagName(script)[0];
        tag.async = 1;
        tag.src = url;
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
      })(
        window,
        document,
        'script',
        '//www.google-analytics.com/analytics.js',
        'ga'
      );
    
      var ga = window.ga;
    
      ga('create', GA_TRACKING_CODE, 'auto');
    
      module.exports = function() {
        return window.ga.apply(window.ga, arguments);
      };
    } else {
      module.exports = function() {console.log(arguments)};
    }
    

提交回复
热议问题