Implementing Google Analytics in Ionic 5 with Capacitor
Asked Answered
D

2

6

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
Davidson answered 14/9, 2020 at 8:27 Comment(1)
ngdevelop.tech/…Alfons
D
13

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');
    }

}
Davidson answered 13/10, 2020 at 8:56 Comment(1)
You could also dynamically insert tracker ID in the analytics service and avoid duplicated links. Adapted from: ngdevelop.tech/…Alfons
G
0

You should use documentation to integrate your iOS and Android application with Google Analytics.

You do not need UA-XXX/G-XXX tracking number nor you need any extra code for this.

However you have to edit and build POD and Gradle files of your app manually in Xcode and Android Studio.

More here on official:

https://support.google.com/analytics/answer/9304153?hl=en#zippy=%2Cios-app-or-android-app

More: https://firebase.google.com/docs/android/setup

Grams answered 4/2, 2022 at 9:15 Comment(2)
The ionic project compiles the app to the requested type, android, iOS, or PWA. If you create PWA you need G-XXX tracking number. In your link: "All other website builders" part where you include gtag.js.... Please read carefully the description of the question. Looks like you are not familiar neither with Ionic/hybrid frameworks nor with Google analyticsDavidson
Yes, for PWA it is a generic include gtag.js, sorry I was solely looking problem for builded apps.Grams

© 2022 - 2024 — McMap. All rights reserved.