簡體   English   中英

跟蹤Angular2中的Google Analytics網頁瀏覽量

[英]Tracking Google Analytics Page Views in Angular2

我使用Angular 2作為前端構建了一個新站點。 由於所有操作都是通過推送狀態完成的,因此沒有頁面加載通常會觸發Google Analytics代碼將頁面視圖發送到Google的服務器。

如何手動向Google發送網頁瀏覽事件,以便跟蹤我網站的哪些用戶正在查看?

我設法通過訂閱路由器上的更改,檢查路由是否實際發生了變化(我有時在某些路由上獲得了多個事件),然后將新路徑發送給Google。

app.component.ts

import { ... } from '...';

// Declare ga function as ambient
declare var ga:Function;

@Component({ ... })

export class AppComponent {
    private currentRoute:string;

    constructor(_router:Router) {
        // Using Rx's built in `distinctUntilChanged ` feature to handle url change c/o @dloomb's answer
        router.events.distinctUntilChanged((previous: any, current: any) => {
            // Subscribe to any `NavigationEnd` events where the url has changed
            if(current instanceof NavigationEnd) {
                return previous.url === current.url;
            }
            return true;
        }).subscribe((x: any) => {
            ga('set', 'page', x.url);
            ga('send', 'pageview')
        });
      }
    }
}

您還需要在加載angular2應用程序之前在主索引文件中包含Google Analytics代碼,以便全局ga對象存在,但您不希望兩次發送初始視圖。 為此,請從GA腳本中刪除以下行

的index.html

<script>
  (function(i,s,o,g,r,a,m){...})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-XXXXXXXX-X', 'auto');
  // Remove this line to avoid sending the first page view twice.
  //ga('send', 'pageview');

</script>
<!-- 
    Load your ng2 app after ga. 
    This style of deferred script loading doesn't guarantee this will happen
    but you can use Promise's or what works for your particular project. 
-->
<script defer type="text/javascript" src="/app.js"></script>

使用第三方庫

作為自己實施GA的替代方案, Angulartics2庫也是實現GA跟蹤的流行工具,也可以與其他分析供應商集成。

擴展伊恩的答案。 您可以使用Rx的內置功能來處理當前路由和新路由之間的區別。

import { NavigationEnd, Router } from '@angular/router';

declare var ga: any;

export class AppComponent {
        constructor(public router: Router) {
            router.events.distinctUntilChanged((previous: any, current: any) => {
                if(current instanceof NavigationEnd) {
                    return previous.url === current.url;
                }
                return true;
            }).subscribe((x: any) => {
                console.log('router.change', x);
                ga('send', 'pageview', x.url);
            });
        }
    }

我們使用distinctUntilChanged運算符使觀察者只發出NavigationEnd類型的項,並且沒有與先前發出的項相同的路由。

如果您在2017年8月之后遇到此問題那么您很可能應該使用gtag.js (Google Universal Analytics全球網站代碼)而不是舊的analytics.js 我建議你在繼續之前檢查migrate from analytics.js和gtag.js頁面之間的差異,以及gtag.js如何在單頁面應用程序中工作。

當您從Google Analytics獲取代碼段時,它看起來像這樣:

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=<%= GOOGLE_ANALYTICS_ID %>"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', '<%= GOOGLE_ANALYTICS_ID %>'); <!-- Remove that one -->
</script>

您需要刪除腳本的最后一行並將其余部分添加到index.html

然后,您必須將從上面的腳本中刪除的行添加到您的代碼中,並將該頁面添加到跟蹤中 基本上它與上面為analytics.js建議的人幾乎相同,但現在你使用gtag.js函數。

例如,如果要跟蹤您在此處打開的所有頁面,請參閱示例代碼:

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import 'rxjs/add/operator/distinctUntilChanged';

// This still has to be declared
declare var gtag: Function;

@Component({
    moduleId: module.id,
    selector: 'my-app',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.css'],
})
export class AppComponent implements OnInit {

    constructor(private router: Router) { }

    ngOnInit() {
        this.router.events.distinctUntilChanged((previous: any, current: any) => {
            // Subscribe to any `NavigationEnd` events where the url has changed
            if(current instanceof NavigationEnd) {
                return previous.url === current.url;
            }
            return true;
        }).subscribe((x: any) => {
            gtag('config', '<%= GOOGLE_ANALYTICS_ID %>', {'page_path': x.url});
        });
    }
}

如果您已閱讀gtag.js的文檔,那么您知道可能有大量的跟蹤選項,但我會關注這里最基本的用法。

在Angular 6中,我建議使用app.component.ts:

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router'
import { Title } from '@angular/platform-browser';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {

  constructor(
    private router: Router,
    private titleService: Title
  ){ }

  ngOnInit() {
     this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        (<any>window).gtag('config', '<%= GOOGLE_ANALYTICS_ID %>', {
          'page_title' : this.titleService.getTitle(),
          'page_path': event.urlAfterRedirects
        });
      }
    });
  }

}

對於index.html:

  <!-- Global site tag (gtag.js) - Google Analytics -->
  <script async src="https://www.googletagmanager.com/gtag/js?id=<%= GOOGLE_ANALYTICS_ID %>"></script>
  <script>
    window.dataLayer = window.dataLayer || [];
    function gtag() { dataLayer.push(arguments); }
    gtag('js', new Date());
  </script>

您可以使用Angular提供的標題服務來管理頁面的標題: https//angular.io/guide/set-document-title

假設每個Angular Route在app.routing.ts都有自己的標題:

   {
    path: 'shop',
    component: ShopComponent,
    data: {
      title: ' == This is Shop Component Title =='
    },
    canActivate: [AuthGuard]
  },

之前提到的解決方案仍會在Google Analytics報告中為每條路線顯示相同的網頁標題。 為了使用相應的Angular Route標題(而不是始終使用index.html <title>標記內容),請在app.component.ts使用以下代碼

  this.router.events.subscribe(event => {

  if (event instanceof NavigationEnd) {
    (<any>window).ga('set', 'page', event.urlAfterRedirects);

    // ----------
    //use the following 3 lines of code to use
    //correnct titles for routes        
    // ----------

    let currentRoute = this.route.root;
    let title = this.getPageTitle(currentRoute);
    (<any>window).ga('set', 'title', title);

    (<any>window).ga('send', 'pageview');

  }
});

...其中getPageTitle方法如下:

getPageTitle = function (currentRoute: ActivatedRoute) {
  let data;
    do {
      const childrenRoutes = currentRoute.children;
      currentRoute = null;
      childrenRoutes.forEach(route => {

      if (route.outlet === 'primary') {
        currentRoute = route;
        data = route.snapshot.data;
      }
    });
  } while (currentRoute);
  return data.title;
};

注意:此解決方案適用於Anguler 5及更低版本。 在Angular 6中,您還可以使用TitleService

this.router.events.subscribe(event => {
    if (event instanceof NavigationEnd) {
        ga('set','page', event.urlAfterRedirects);
        ga('send', 'pageview');
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM