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


如果你在Angular应用中使用ng-view,你可以监听$viewContentLoaded事件,并将跟踪事件推送到谷歌Analytics。

假设你已经在主index.html文件中设置了跟踪代码,名称为var _gaq, MyCtrl是你在ng-controller指令中定义的。

function MyCtrl($scope, $location, $window) {
  $scope.$on('$viewContentLoaded', function(event) {
    $window._gaq.push(['_trackPageView', $location.url()]);
  });
}

更新: 新版本的谷歌分析使用这个

function MyCtrl($scope, $location, $window) {
  $scope.$on('$viewContentLoaded', function(event) {
    $window.ga('send', 'pageview', { page: $location.url() });
  });
}

当AngularJS中加载一个新视图时,谷歌Analytics不会将其计算为新页面加载。幸运的是,有一种方法手动告诉GA日志url作为一个新的页面视图。

_gaq。push ([' _trackPageview ', ' < url > ']);可以完成这项工作,但是如何将它与AngularJS绑定呢?

这里有一个你可以使用的服务:

(function(angular) { 

  angular.module('analytics', ['ng']).service('analytics', [
    '$rootScope', '$window', '$location', function($rootScope, $window, $location) {
      var track = function() {
        $window._gaq.push(['_trackPageview', $location.path()]);
      };
      $rootScope.$on('$viewContentLoaded', track);
    }
  ]);

}(window.angular));

当你定义你的angular模块时,像这样包含analytics模块:

angular.module('myappname', ['analytics']);

更新:

您应该使用新的通用谷歌分析跟踪代码:

$window.ga('send', 'pageview', {page: $location.url()});

我用上面的方法在github上创建了一个简单的例子。

https://github.com/isamuelson/angularjs-googleanalytics


我已经创建了一个服务+过滤器,可以帮助你们,如果你选择在未来添加其他提供商,也许也可以帮助他们。

登录https://github.com/mgonto/angularytics,让我知道你是怎么做的。


如果有人想实现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()]);
      });
    }
  };
});

只是一个简单的补充。如果你正在使用新的analysis .js,那么:

var track = function() {     
 ga('send', 'pageview', {'page': $location.path()});                
};

另外一个提示是谷歌分析不会在本地主机上发射。因此,如果您在本地主机上进行测试,请使用以下代码而不是默认的create(完整文档)

ga('create', 'UA-XXXX-Y', {'cookieDomain': 'none'});

app.run(function ($rootScope, $location) {
    $rootScope.$on('$routeChangeSuccess', function(){
        ga('send', 'pageview', $location.path());
    });
});

如果你正在寻找谷歌Analytics的新跟踪代码的完全控制,你可以使用我自己的Angular-GA。

它使ga可以通过注入得到,因此易于测试。除了在每个routeChange上设置路径外,它没有做任何神奇的事情。你还是需要像这样发送浏览量。

app.run(function ($rootScope, $location, ga) {
    $rootScope.$on('$routeChangeSuccess', function(){
        ga('send', 'pageview');
    });
});

另外,还有一个指令ga,它允许将多个分析函数绑定到事件上,就像这样:

<a href="#" ga="[['set', 'metric1', 10], ['send', 'event', 'player', 'play', video.id]]"></a>

我使用ui-router和我的代码看起来像这样:

$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams){
  /* Google analytics */
  var path = toState.url;
  for(var i in toParams){
    path = path.replace(':' + i, toParams[i]);
  }
  /* global ga */
  ga('send', 'pageview', path);
});

这样我就可以跟踪不同的状态。也许有人会觉得它有用。


把wynnwu和dpineda的答案结合起来对我来说很有用。

angular.module('app', [])
  .run(['$rootScope', '$location', '$window',
    function($rootScope, $location, $window) {
      $rootScope.$on('$routeChangeSuccess',
        function(event) {
          if (!$window.ga) {
            return;
          }
          $window.ga('send', 'pageview', {
            page: $location.path()
          });
        });
    }
  ]);

将第三个参数设置为一个对象(而不仅仅是$location.path()),并使用$routeChangeSuccess而不是$stateChangeSuccess就可以了。

希望这能有所帮助。


在index.html中,复制并粘贴ga代码片段,但去掉ga('send', 'pageview');

<!-- Google Analytics: change UA-XXXXX-X to be your site's ID -->
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-XXXXXXXX-X');
</script>

我喜欢给它自己的工厂文件my-google-analytics.js加上自我注入:

angular.module('myApp')
  .factory('myGoogleAnalytics', [
    '$rootScope', '$window', '$location', 
    function ($rootScope, $window, $location) {

      var myGoogleAnalytics = {};

      /**
       * Set the page to the current location path
       * and then send a pageview to log path change.
       */
      myGoogleAnalytics.sendPageview = function() {
        if ($window.ga) {
          $window.ga('set', 'page', $location.path());
          $window.ga('send', 'pageview');
        }
      }

      // subscribe to events
      $rootScope.$on('$viewContentLoaded', myGoogleAnalytics.sendPageview);

      return myGoogleAnalytics;
    }
  ])
  .run([
    'myGoogleAnalytics', 
    function(myGoogleAnalytics) {
        // inject self
    }
  ]);

结合佩德罗·洛佩兹的回答,

我把这个添加到我的ngGoogleAnalytis模块(我在许多应用程序中重用):

var base = $('base').attr('href').replace(/\/$/, "");

在这种情况下,我有一个标签在我的索引链接:

  <base href="/store/">

当在angular.js v1.3上使用html5模式时,它很有用

(如果base标签没有以斜杠/结束,则删除replace()函数调用)

angular.module("ngGoogleAnalytics", []).run(['$rootScope', '$location', '$window',
    function($rootScope, $location, $window) {
      $rootScope.$on('$routeChangeSuccess',
        function(event) {
          if (!$window.ga) { return; }
          var base = $('base').attr('href').replace(/\/$/, "");

          $window.ga('send', 'pageview', {
            page: base + $location.path()
          });
        }
      );
    }
  ]);

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

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


如果你正在使用ui-router,你可以像这样订阅$stateChangeSuccess事件:

$rootScope.$on('$stateChangeSuccess', function (event) {
    $window.ga('send', 'pageview', $location.path());
});

有关完整的工作示例,请参阅这篇博客文章


我个人喜欢用模板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的使用非常陌生,所以不太确定这是否是最好的方法。


使用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


对于那些使用AngularUI路由器而不是ngRoute的人来说,可以使用下面的代码来跟踪页面视图。

app.run(function ($rootScope) {
    $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
        ga('set', 'page', toState.url);
        ga('send', 'pageview');
    });
});

开发人员创建单页应用程序可以使用autotrack,其中包括一个urlChangeTracker插件,该插件可以处理本指南中列出的所有重要考虑事项。有关使用和安装说明,请参阅autotrack文档。


我在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);

我发现gtag()函数工作,而不是ga()函数。

在index.html文件中,<head>部分:

<script async src="https://www.googletagmanager.com/gtag/js?id=TrackingId"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'TrackingId');
</script>

在AngularJS代码中:

app.run(function ($rootScope, $location) {
  $rootScope.$on('$routeChangeSuccess', function() {
    gtag('config', 'TrackingId', {'page_path': $location.path()});
  });
});

用您自己的跟踪Id替换TrackingId。