我正在使用AngularJS作为前端设置一个新的应用程序。客户端上的一切都是用HTML5推送状态完成的,我希望能够在谷歌分析中跟踪我的页面视图。


当前回答

使用GA 'set'来确保路由被谷歌实时分析拾取。否则,后续对GA的调用将不会显示在实时面板中。

$scope.$on('$routeChangeSuccess', function() {
    $window.ga('set', 'page', $location.url());
    $window.ga('send', 'pageview');
});

谷歌强烈建议使用这种方法,而不是在send中传递第三个参数。 https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications

其他回答

使用GA 'set'来确保路由被谷歌实时分析拾取。否则,后续对GA的调用将不会显示在实时面板中。

$scope.$on('$routeChangeSuccess', function() {
    $window.ga('set', 'page', $location.url());
    $window.ga('send', 'pageview');
});

谷歌强烈建议使用这种方法,而不是在send中传递第三个参数。 https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications

我在html5模式下使用AngluarJS。我发现以下解决方案是最可靠的:

使用angular-google-analytics库。用如下代码初始化它:

//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);
  }
]);

之后,在$stateChangeSuccess上添加监听器,并发送trackPage事件。

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
            }
        });
    }
]);

在任何时候,当你的用户初始化时,你可以在那里注入分析并调用:

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

如果有人想实现using指令,那么就在index.html中标识(或创建)一个div(就在body标签下面,或在相同的DOM级别)。

<div class="google-analytics"/>

然后在指令中添加如下代码

myApp.directive('googleAnalytics', function ( $location, $window ) {
  return {
    scope: true,
    link: function (scope) {
      scope.$on( '$routeChangeSuccess', function () {
        $window._gaq.push(['_trackPageview', $location.path()]);
      });
    }
  };
});

做到这一点的最好方法是使用谷歌标签管理器来根据历史侦听器发射谷歌分析标签。这些都内置在GTM接口中,可以轻松地跟踪客户端HTML5交互。

启用内置的History变量并创建触发器来根据历史更改触发事件。

我个人喜欢用模板URL而不是当前路径来设置我的分析。这主要是因为我的应用程序有许多自定义路径,如message/:id或profile/:id。如果我要发送这些路径,我将在分析中有如此多的页面被查看,这将很难检查哪个页面用户访问最多。

$rootScope.$on('$viewContentLoaded', function(event) {
    $window.ga('send', 'pageview', {
        page: $route.current.templateUrl.replace("views", "")
    });
});

我现在在我的分析中获得干净的页面视图,如user-profile.html和message.html,而不是许多页面是profile/1, profile/2和profile/3。我现在可以通过处理报告来查看有多少人正在浏览用户资料。

如果有人对为什么这是一种糟糕的分析实践有任何异议,我很乐意听听。对谷歌Analytics的使用非常陌生,所以不太确定这是否是最好的方法。