了解您的使用者並衡量使用者行為是應用程式開發的重要步驟。遺憾的是,在用 Capacitor 包裝您的行動應用程式後,要讓 Google Analytics 運作需要一些非標準的工作。在純 Web 應用程式中設定 Google Analytics 非常容易,但 Capacitor 在某種程度上阻止了頁面瀏覽和事件傳送到 Google Analytics。
請依照本指南在您 Capacitor 驅動的 Quasar 應用程式中實作 Google Analytics。
警告
您需要在 /index.html
中包含 Google 提供的 <script>
標籤,這會使您的應用程式依賴網際網路連線!
先決條件
- 請確保您的所有路由都已指定名稱和路徑參數。否則,它們無法發佈到
ga.logPage
函數。請參閱路由以取得更多關於路由的資訊。 - 具備 Google Analytics 的基本知識
準備工作
在我們開始在您的應用程式中實作 Google Analytics 之前,您需要一個 Google Analytics 和 Google Tag Manager 的帳戶。所以我們先做這個。當您擁有這些帳戶後,就可以設定 Tag Manager 了。請按照這篇 Multiminds 文章 中的步驟進行設定。
在應用程式中實作
在本指南中,我們假設您有一個固定的 sessionId,您將其發送到 Google Analytics。Google Analytics 使用 sessionId 來區分不同的使用者。如果您想建立匿名 sessionId,請參閱關於使用者 ID 的 Analytics 文件。
將 Tag Manager 代码片段放入您的 index.html
文件的
analytics.js
的新檔案,內容如下export default {
logEvent(category, action, label, sessionId = null) {
window.dataLayer.push({
appEventCategory: category,
appEventAction: action,
appEventLabel: label,
sessionId: sessionId
})
window.dataLayer.push({ 'event': 'appEvent' })
},
logPage(path, name, sessionId = null) {
window.dataLayer.push({
screenPath: path,
screenName: name,
sessionId: sessionId
})
window.dataLayer.push({ 'event': 'appScreenView' })
}
}
為了確保您應用程式中的所有頁面都自動發佈到 Google Analytics,我們建立一個應用程式啟動檔案
$ quasar new boot google-analytics [--format ts]
然後我們編輯新建立的檔案:/src/boot/google-analytics.js
import ga from 'analytics.js'
export default ({ router }) => {
router.afterEach((to, from) => {
ga.logPage(to.path, to.name, sessionId)
})
}
最後,我們在 /quasar.config
檔案中註冊應用程式啟動檔案。如果我們需要,可以僅針對 Capacitor 包裝的應用程式執行此操作
boot: [
ctx.mode.capacitor ? 'google-analytics' : ''
]
更多關於事件的資訊可以在關於事件的 Analytics 文件中找到。
當您執行您的應用程式時,您將會看到事件和頁面瀏覽量進來。頁面瀏覽量通常需要 5 到 10 秒才能在即時檢視中註冊。