UniApp使用Google统计

发表于 2022-01-23  6.88k 次阅读


首先在npm内引入,也可以在dcloud插件市场里面下载,

npm install @ouduidui/ga-tracker

然后再在main.js或者app.js内引入这些(请根据自身情况修改)

import {GoogleAnalytics , HitBuilders} from "@ouduidui/ga-tracker";//Google 统计

Vue.prototype.ga = function(){
	const analytic = this.$gaTracker.getInstance()
	var pages = getCurrentPages() // 获取栈实例
	let currentPage = pages[pages.length - 1]['$page']['fullPath'] //当前页面路径(带参数)
	analytic.setScreenName("/pwa#" + currentPage);
	analytic.send(new HitBuilders.ScreenViewBuilder().build()); //上报
}//google统计

const gaTracker = {
    instance: null,
    getInstance() {
        if (!this.instance) {
			// 初始化GoogleAnalytics Tracker
			// #ifdef APP-PLUS 
			this.instance = GoogleAnalytics.getInstance() 
                .setAppName('uni-app')   // 设置名称
                .setAppVersion(plus.runtime.version)   // 设置版本号
                .newTracker('UA-XXXXXXX-1');  // 设置跟踪ID
			// #endif
			// #ifdef H5
            this.instance = GoogleAnalytics.getInstance() 
                .setAppName('uni-app')   // 设置名称
                .setAppVersion('PWA')   // 设置版本号
                .newTracker('UA-XXXXXXXX-1');  // 设置跟踪ID
			// #endif
        }
        return this.instance;
    }
}
Vue.prototype.$gaTracker = gaTracker;

最后,在你需要统计的页面中的onload函数写入如下代码

this.ga()

如果你是开发小程序的话,我们需要将上报域名设置为白名单。但是www.google-analytics.com域名没有国内备案,无法添加到微信小程序的request合法域名中。

因此你需要自己有一个已备案域名,然后用起或者二级域名去重定向到www.google-analytics.com

具体在初始化GA中的那一坨中加入如下内容

// #ifdef MP-WEIXIN
// 使用自己的合法域名做跟踪数据转发
this.instance.setTrackerServer("https://ga-proxy.example.com");
// #endif

顺带一提,老版GA已经不能直接创建移动应用类型的媒体资源了,他会提示你链接Firebase,你可以先创建一个网页类型的媒体资源,然后再创建移动应用类型的媒体资源子项,当然你也可以套用以前的媒体资源,具体怎么做取决于你,当然在进行网页+移动应用混合统计的时候,别忘了对移动应用媒体资源子项进行筛选器设置。

此文章允许规范转载,请把我的名字江程训署名上


纵使代码万千行