How to Implement Google Analytics in Ionic 5 Application using Ionic Native and Cordova Plugins

Last updated on by Digamber

This tutorial is going to help you learn how to implement Google Analytics in Ionic 5 and Angular application using Ionic Native and Cordova plugins from scratch.

Google Analytics is a great web analytics tool developed and offered by Google for analysing web site traffic. It can help to track session duration, pages per session, bounce rate etc. Real-Time Analytics is implied in GA, enabling a user to have insight about visitors currently on the site.

Not just that if you are a marketer or even an analyst, then you can create an excellent marketing strategy. So it is not wrong to say Its a boon from a marketing perspective.

Google Analytics has innumerable benefits, but we are specifically focusing on enabling GA for an Ionic application. Also, we will see how to configure event tracking for Google Analytics for mobile applications.

Getting Started

Ionic CLI is a must have tool, this command-line tool lets you work on Ionic platform.

Run command to create the Ionic app.

npm install -g @ionic/cli

Once Ionic CLI installed, then execute the command to install the Ionic project. You can skip this step if the app is already installed.

ionic start ionic-google-analytics-example sidemneu --type=angular

Get inside the project:

cd ionic-google-analytics-example

Install Ionic Native and Cordova Google Analytics Plugins

To track site visitors through Google Analytics in Ionic 5 is simpler with Ionic Native and Cordova Google Analytics Plugins.

Add both the plugins simultaneously with the following command:

ionic cordova plugin add cordova-plugin-google-analytics

npm install @ionic-native/google-analytics

You will astonish with both the performance of the plugin not just that it also supports various platforms such as Android, iOS, Windows Phones and Browser.

Import Google Analytics Plugin in AppModule

First, open the app/app.module.ts file, import the GoogleAnalytics from ‘@ionic-native/google-analytics/ngx’ then inject GoogleAnalytics in providers array.

// app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

import { GoogleAnalytics } from '@ionic-native/google-analytics/ngx';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    AppRoutingModule
  ],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    GoogleAnalytics
  ],
  bootstrap: [AppComponent]
})

export class AppModule {}

Integrating Google Analytics in Ionic

Adding or implementing Google Analytics is more superficial, in this segment of the tutorial, we will incorporate the GA tracking code in the Ionic application to keep an eye on-site visitors.

Consequently open the app.component.ts file, in here we will place the given below logic. It will help us keep the site visitor information with the help of GA tracking code.

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 { GoogleAnalytics } from '@ionic-native/google-analytics/ngx';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent {
  public appPages = [
    {
      title: 'Inbox',
      url: '/folder/Inbox',
      icon: 'mail'
    },
    {
      title: 'Outbox',
      url: '/folder/Outbox',
      icon: 'paper-plane'
    }
  ];

  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private ga: GoogleAnalytics
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();

      this.ga.startTrackerWithId('UA-XXXXXXXXXX-X')
      .then(() => {
        console.log('Google analytics is ready now');
        this.ga.trackView('Outbox') 
        .then(() => {

        })
        .catch(
          error => console.log(error)
        );  
       }).catch(
        error => console.log('Google Analytics Error: ' + error)
      );
      
    });
  }

  // Track an event:
  trackEvent(val) {
    // Label and Value are optional, Value is numeric
    this.ga.trackEvent('Category', 'Action', 'Label', val)
  }  

}

The startTrackerWithId method of Google Analytics invokes the site tracking and displays the tracking related information in the GA dashboard.

The trackView() method sets the tracking for screen.

Generically, as the name suggests, the trackEvent method delicately tracks the event.

To view the Google Analytics in action run your application in real device and go to GA dashboard to monitor the web site tracking.

Summary

Ultimately, we have finished the Ionic 5 Google Analytics tutorial; we have barely scratched the surface; however, we have seen how to easily integrate Google Analytics in Ionic 5 application using Cordova and Ionic Native plugins. Apparently, this is just the tip of the iceberg; Google Analytics service provides tons of method that can make your tracking job easy.

You can check out more about Google Analytics methods and properties here.