Tracking Google Analytics Page Views with AngularJS

前端 未结 21 905
北恋
北恋 2020-11-27 09:14

I\'m setting up a new app using AngularJS as the frontend. Everything on the client side is done with HTML5 pushstate and I\'d like to be able to track my page views in Goog

21条回答
  •  [愿得一人]
    2020-11-27 09:38

    I am using AngluarJS in html5 mode. I found following solution as most reliable:

    Use angular-google-analytics library. Initialize it with something like:

    //Do this in module that is always initialized on your webapp    
    angular.module('core').config(["AnalyticsProvider",
      function (AnalyticsProvider) {
        AnalyticsProvider.setAccount(YOUR_GOOGLE_ANALYTICS_TRACKING_CODE);
    
        //Ignoring first page load because of HTML5 route mode to ensure that page view is called only when you explicitly call for pageview event
        AnalyticsProvider.ignoreFirstPageLoad(true);
      }
    ]);
    

    After that, add listener on $stateChangeSuccess' and send trackPage event.

    angular.module('core').run(['$rootScope', '$location', 'Analytics', 
        function($rootScope, $location, Analytics) {
            $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams, options) {
                try {
                    Analytics.trackPage($location.url());
                }
                catch(err) {
                  //user browser is disabling tracking
                }
            });
        }
    ]);
    

    At any moment, when you have your user initalized you can inject Analytics there and make call:

    Analytics.set('&uid', user.id);
    

提交回复
热议问题