了解您的使用者並衡量使用者行為是應用程式開發的重要步驟。 然而,在用 Cordova 包裝您的行動應用程式後,要讓 Google Analytics 運作需要一些非標準的工作。 在純 Web 應用程式中設定 Google Analytics 非常容易,但 Cordova 在某種程度上會阻止網頁瀏覽和事件傳送到 Google Analytics。
按照本指南將 Google Analytics 實作到您的 Cordova 驅動的 Quasar 應用程式中。
您可能也想閱讀本教學:Cordova 應用程式的 Google Analytics 設定。
警告
您需要在 /index.html 或 /src/index.template.html 中包含 Google 提供的 <script>
標籤,這會使您的應用程式依賴網際網路連線!
先決條件
- 確保您的所有路由都指定了名稱和路徑參數。 否則,它們無法發佈到
ga.logPage
函數。 請參閱路由以取得更多路由資訊。 - 具備 Google Analytics 的基本知識
準備
在我們可以開始將 Google Analytics 實作到您的應用程式之前,您需要一個 Google Analytics 和 Google Tagmanager 的帳戶。 所以我們先這樣做。 當您擁有這些帳戶後,就該設定 Tag Manager 了。 請按照這篇 Multiminds 文章 中的步驟進行。
將此實作到應用程式中
在本指南中,我們假設您有一個固定的 sessionId,您將其傳送到 Google Analytics。 Google Analytics 使用 sessionId 來區分不同的使用者。 如果您想建立匿名 sessionId,請參閱關於使用者 ID 的 Analytics 文件。
將 Tag Manager 代码片段放入 index.html
檔案的 <head> 中(如果您已按照 Multiminds 文章 中的步驟操作,您已經有了)。 在您的程式碼庫中建立一個名為 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
檔案中註冊應用程式啟動檔案。 如果我們願意,我們可以僅針對 Cordova 包裝的應用程式執行此操作。
boot: [
ctx.mode.cordova ? 'google-analytics' : ''
]
更多關於事件的資訊可以在關於事件的 Analytics 文件中找到。
當您執行您的應用程式時,您會看到事件和網頁瀏覽傳入。 網頁瀏覽通常需要大約 5 到 10 秒才能在即時檢視中註冊。