首页 文章

使用AngularJS跟踪Google Analytics网页浏览量

提问于
浏览
218

我正在使用AngularJS作为前端设置一个新的应用程序 . 客户端的所有内容都使用HTML5 pushstate完成,我希望能够在Google Analytics中跟踪我的网页浏览量 .

20 回答

  • 1

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

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

    如果您在Angular应用中使用 ng-view ,则可以收听 $viewContentLoaded 事件并将跟踪事件推送到Google Analytics .

    假设您已在主index.html文件中设置了跟踪代码,其名称为 var _gaq ,而MyCtrl就是您在 ng-controller 指令中定义的内容 .

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

    UPDATE: for google-analytics的新版本使用此版本

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

    AngularJS 中加载新视图时,Google Analytics不会将其视为新的网页加载 . 幸运的是,有一种方法可以手动告知GA将网址记录为新的网页浏览 .

    _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.module('myappname', ['analytics']);
    

    UPDATE

    您应该使用新的Universal Google Analytics跟踪代码:

    $window.ga('send', 'pageview', {page: $location.url()});
    
  • 236
    app.run(function ($rootScope, $location) {
        $rootScope.$on('$routeChangeSuccess', function(){
            ga('send', 'pageview', $location.path());
        });
    });
    
  • 0

    只是一个快速添加 . 如果您正在使用新的analytics.js,那么:

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

    另外一个提示是Google解析不会在localhost上触发 . 因此,如果您在localhost上进行测试,请使用以下代替默认创建(full documentation

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

    我已经创建了一个服务过滤器,可以帮助你们这个,如果你选择在将来添加它们,也可以和其他一些提供商一起使用 .

    查看https://github.com/mgonto/angularytics并告诉我这是如何为您解决的 .

  • -3

    通过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就可以了 .

    希望这可以帮助 .

  • 4

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

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

  • 3

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

    最好的方法是使用Google跟踪代码管理器根据历史记录侦听器触发您的Google Analytics代码 . 它们内置于GTM界面,可轻松跟踪客户端HTML5交互 .

    启用内置历史记录变量并创建触发器以根据历史记录更改触发事件 .

  • 2

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

    如果您正在使用ui-router,您可以订阅$ stateChangeSuccess事件,如下所示:

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

    有关完整的工作示例,请参阅this blog post

  • 4

    使用GA'set'确保为Google实时分析选择路线 . 否则,对GA的后续调用将不会显示在实时面板中 .

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

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

  • 0

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

    在任何时候,当您的用户进行初始化时,您可以在那里注入Google Analytics并拨打电话:

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

    我使用的是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);
    });
    

    这样我就可以跟踪不同的状态 . 也许有人会发现它很有用 .

  • 11

    我发现 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()});
      });
    });
    

    TrackingId 替换为您自己的跟踪ID .

  • 3

    创建单页应用程序的开发人员可以使用autotrack,其中包含一个urlChangeTracker插件,可以为您处理本指南中列出的所有重要注意事项 . 有关使用和安装说明,请参阅autotrack documentation .

  • 2

    与佩德罗·洛佩兹的回答更加融合,

    我将此添加到我的ngGoogleAnalytis模块(我在许多应用程序中重复使用):

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

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

    <base href="/store/">
    

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

    (如果您的基本标记没有以斜杠/结尾),请删除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()
              });
            }
          );
        }
      ]);
    
  • 57

    我个人喜欢使用模板URL而不是当前路径来设置我的分析 . 这主要是因为我的应用程序有许多自定义路径,例如 message/:idprofile/:id . 如果我要发送这些路径,我会在分析中查看这么多页面,要检查用户访问的页面是否太难 .

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

    我现在可以在我的分析中获得干净的页面视图,例如 user-profile.htmlmessage.html ,而不是许多页面 profile/1profile/2profile/3 . 我现在可以处理报告以查看有多少人正在查看用户 Profiles .

    如果有人对为什么这是分析中的不良做法有任何异议,我会非常乐意听到它 . 使用Google Analytics这一点非常新,所以不太确定这是否是最佳方法 .

  • 1

    如果您正在寻找对Google Analytics新跟踪代码的完全控制权,您可以使用我自己的Angular-GA .

    它通过注入使 ga 可用,所以除了在每个routesChange上设置路径之外,它还可以做任何魔术 . 您仍然需要像这里发送网页浏览 .

    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>
    

相关问题