I am trying to implement the GA on an ionic project for days now without any luck.
import { Plugins } from '@capacitor/core';
const { GoogleAnalytics } = Plugins;
...
initializeApp() {
GoogleAnalytics.startTrackerWithId('G-0000000000')
.then(() => {
alert('Google analytics is ready now');
})
.catch(e => alert(e));
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');
}
}
First install the plugin
npm install cordova-plugin-google-analytics
npm install @ionic-native/google-analytics
ionic cap sync
Then
import { GoogleAnalytics } from '@ionic-native/google-analytics/ngx';
constructor(private ga: GoogleAnalytics) { }
this.ga.startTrackerWithId('YOUR_TRACKER_ID')
.then(() => {
console.log('Google analytics is ready now');
this.ga.trackView('test');
// Tracker is ready
// You can now track pages or set additional information such as AppVersion or UserId
})
.catch(e => console.log('Error starting GoogleAnalytics', e));
You should use documentation to integrate your iOS and Android application with Google Analytics.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.