npm install @ouduidui/ga-tracker
- 在跟踪器上设置自定义跟踪服务器
tracker.setTrackerServer("https://ga-proxy.example.com")
- 修改域名
example.com
的DNS记录,将ga-proxy.example.com
指向你自己的服务器IP - 自己服务器上的
nginx
做如下配置 -
upstream real_ga_servers { server www.google-analytics.com:443 weight=5 max_fails=0; keepalive 64; } server { listen 443 ssl; server_name ga-proxy.example.com; ssl on; # 设置ssl证书(略) location / { # 告诉ga用户真实ip rewrite ^(.*)$ $1?uip=$remote_addr break; proxy_set_header Host www.google-analytics.com; # Proxy to google-analytics.com proxy_buffering off; # 使用keepalive proxy_http_version 1.1; # require nginx > 1.1.4 proxy_set_header Connection ""; # for keepalive upstream proxy_pass https://real_ga_servers; proxy_redirect off; } }
main.js引入
import {GoogleAnalytics} from "@ouduidui/ga-tracker";
const gaTracker = {
instance: null,
getInstance() {
if (!this.instance) {
// 初始化GoogleAnalytics Tracker
this.instance = GoogleAnalytics.getInstance()
.setAppName('UniApp') // 设置名称
.setAppVersion('1.0.0') // 设置版本号
.newTracker('UA-XXXXXX-X'); // 设置跟踪ID
// #ifdef MP-WEIXIN
// 使用自己的合法域名做跟踪数据转发
this.instance.setTrackerServer("https://ga-proxy.example.com");
// #endif
}
return this.instance;
},
}
Vue.prototype.$gaTracker = gaTracker;
使用方法
<template>
<view class="content">
<image class="logo" src="/static/logo.png"></image>
<view>
<text class="title">{{title}}</text>
</view>
</view>
</template>
<script>
import {HitBuilders} from "@ouduidui/ga-tracker";
export default {
data() {
return {
title: 'Hello'
}
},
() {
// 设置屏幕名称
const t = this.$gaTracker.getInstance()
t.setScreenName('这是我的首屏页');
// 或者对应相应字段
t.set('xx',val)
// 上报
t.send(new HitBuilders.ScreenViewBuilder().build());
}
}
</script>