Search code examples
angularcordovaionic-frameworkgoogle-analyticscapacitor

Implementing Google Analytics in Ionic 5 with Capacitor


I am trying to implement the GA on an ionic project for days now without any luck.

I need this to work in the browser (PWA) and Android platforms.

Let's start with what docs say: https://ionicframework.com/docs/native/google-analytics

Capacitor:

npm install cordova-plugin-google-analytics

npm install @ionic-native/google-analytics

ionic cap sync

import { Plugins } from '@capacitor/core';
const { GoogleAnalytics } = Plugins;

... 

initializeApp() {
    GoogleAnalytics.startTrackerWithId('G-0000000000')
    .then(() => {
        alert('Google analytics is ready now');
    })
   .catch(e => alert(e));

After this I get the following error :

GoogleAnalytics does not have web implementation.

If I do the Cordova implementation all I got is that cordova_not_available

Tried to register the WebPlugin

import { Plugins } from '@capacitor/core';
import { registerWebPlugin } from '@capacitor/core';
const { GoogleAnalytics } = Plugins;
registerWebPlugin(GoogleAnalytics);

However, the compiler threw an error

ERROR in app.component.ts:159:25 - error TS2345: 
Argument of type '{ [prop: string]: any; }' is not assignable to parameter of type 'WebPlugin'.
Type '{ [prop: string]: any; }' is missing the following properties from type 
'WebPlugin': config, loaded, listeners, windowListeners, and 9 more. 

Why do I get these errors when docs say it supposed to work in the browser(PWA) ?

Ionic info:

Ionic CLI                     : 5.4.16
Ionic Framework               : @ionic/angular 5.3.2
@angular-devkit/build-angular : 0.1001.1
@angular-devkit/schematics    : 8.1.3
@angular/cli                  : 10.1.1
@ionic/angular-toolkit        : 2.3.3

Capacitor CLI   : 1.5.3
@capacitor/core : 1.5.3

Cordova CLI       : 9.0.0 ([email protected])
Cordova Platforms : android 8.1.0, browser 6.0.0
Cordova Plugins   : cordova-plugin-ionic-keyboard 2.2.0, cordova-plugin-ionic-webview 4.2.1, (and 12 
other plugins)

cordova-res (update available: 0.15.1) : 0.9.0
native-run (update available: 1.0.0)   : 0.2.9


Android SDK Tools : 26.1.1
NodeJS            : v12.13.1
npm               : 6.12.1
OS                : Windows 10

Solution

  • So basically, first of all, I needed to use google gtag. Neither Cordova nor Capacitor could solve my problem. I used "simple JS include" approach.

    index.html

    Add tracking code to the header

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

    Create a service for gtag/analytics

    ./providers/analytics/analytics.service.ts

    import { Injectable } from '@angular/core';
    declare var gtag;
    
    @Injectable({
      providedIn: 'root'
    })
    export class AnalyticsService {
    
      constructor() { }
    
      startTrackerWithId(id) {
        gtag('config', id);
      }
    
      trackView(pageUrl: string, screenName: string) {}
    
      trackEvent(category, action, label?, value?) {}
    }
    

    app.module.ts

    Add AnalyticsService to the providers

    import { AnalyticsService } from './providers/analytics/analytics.service';
    
    @NgModule({
        declarations: [AppComponent, NotificationsComponent],
        imports: [ ... ... ],
        entryComponents: [NotificationsComponent],
        providers: [
          ...
          AnalyticsService,
          ...
       ],
       bootstrap: [AppComponent]
    })
    export class AppModule {}
    

    app.component.ts

    import { AnalyticsService } from './providers/analytics/analytics.service';
    
    export class AppComponent implements OnInit, OnDestroy {
    
        constructor(
            ...
            private analyticsService: AnalyticsService,
            ...
        ) {
          this.initializeApp();
        }
    
       ...
    
        initializeApp() {
             this.analyticsService.startTrackerWithId('G-XXXXXXXXXX');
        }
    
    }