LoginSignup
2
3

More than 5 years have passed since last update.

Ionic4 に Google Analytics を入れる

Last updated at Posted at 2019-04-14

初めに

ionic4 でPWAアプリを開発しようとした際、Ionic の公式サイトで記述されている
方法で、Google Analytics がうまく導入できずに困ったときのために
この記事を書きていきます。

Ionic4 のプロジェクトを制作する

始めるにあたり、Ionic CLI を使い、プロジェクトを作成します。
その際、テンプレートはどれでも構いませんが、
フレームワークは、Angularで進めていきます。

ionic start Example  

Google Analytics を導入する

それでは、実際に導入していきたいと思います。
ここでは、Google Analytics での登録完了後、トラフィックコード: UA-XXXXXXXXX-Y が発行されますので,こちらを保存してください。

進めていくうえで参考にしたサイトはこちらになります。

プロジェクト ”Example” 作成後、

cd Example
ionic g service gs

とコマンドを入力してください。入力後、
ga.service.ts, を編集します。

ga.service.ts
import { Injectable } from '@angular/core';

declare let gtag:any;
@Injectable({
  providedIn: 'root'
})
export class GaService {

  constructor() { }

  private useGA():boolean{
    return typeof gtag!==undefined;
  }
  sendPageView(url:string):void{
    if(!this.useGA()){return;}
    gtag('config','UA-XXXXXXXXX-Y',{
    //'UA-XXXXXXXXX-Y'には、生成されたコードを入力してください。
    'page-path':url 
    });
  }
  sendEvent(eventName:string,
            eventCategory:string,
            eventAction:string,
            eventLabel:any):void{
    if(!this.useGA()){ return; }
    gtag('event',eventName,{
      event_category:eventCategory,
      event_action:eventAction,
      event_label:eventLabel
    });
  }
}

次に、app.compornent.tsを編集します。

app.compornent.ts

import { Component } from '@angular/core';
import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { Router,NavigationEnd } from '@angular/router';
import { GaService } from './ga.service';
import { filter } from 'rxjs/operators';

declare let ga: Function;

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {
  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private router:Router,
    private gaService :GaService

  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      this.router.events
      .pipe(
       filter(e=>e instanceof NavigationEnd))
      .subscribe((params: any)=>{
        this.gaService.sendPageView(params.url);
      });

    });
  }
}

最後に、index.htmlに、次のコードをhead内に追加してください。

index.html
<head>
 ...
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-Y"></script>
  <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
  </script>
 ...
</head>

これにより、Google Analytics の準備はできました。
このコードをデプロイした後、Google Analytics で、
現在の利用者が1人とカウントされていたら成功です。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3