[英]Implementing Google Analytics in Ionic 5 with Capacitor
我正在嘗試在離子項目上實施 GA 幾天,但沒有任何運氣。
我需要它在瀏覽器 (PWA) 和 Android 平台上工作。
讓我們從文檔所說的開始: https<\/a> :\/\/ionicframework.com\/docs\/native\/google-analytics
電容器:
import { Plugins } from '@capacitor/core';
const { GoogleAnalytics } = Plugins;
...
initializeApp() {
GoogleAnalytics.startTrackerWithId('G-0000000000')
.then(() => {
alert('Google analytics is ready now');
})
.catch(e => alert(e));
所以基本上,首先,我需要使用 google gtag
。 Cordova 和 Capacitor 都無法解決我的問題。 我使用了“簡單的 JS 包含”方法。
索引.html
將跟蹤代碼添加到標題
<!-- 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 -->
為 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
將 AnalyticsService 添加到提供程序
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');
}
}
首先安裝插件
npm install cordova-plugin-google-analytics
npm install @ionic-native/google-analytics
ionic cap sync
然后
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));
您應該使用文檔將您的 iOS 和 Android 應用程序與 Google Analytics 集成。
您不需要 UA-XXX\/G-XXX 跟蹤號,也不需要任何額外的代碼。
但是,您必須在 Xcode 和 Android Studio 中手動編輯和構建應用程序的 POD 和 Gradle 文件。
更多官方信息:
https:\/\/support.google.com\/analytics\/answer\/9304153?hl=en#zippy=%2Cios-app-or-android-app<\/a>
更多: https<\/a> :\/\/firebase.google.com\/docs\/android\/setup
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.