Google Analytics Api 使用
最近在做浏览器扩展《温故知新》的新版本。其中,最让我头疼的就是用 Google Analytics 统计信息了。
Google 官方提供的 SDK 使用的话,需要外部引入 SDK,并且配置 CSP,而 Firefox 浏览器不允许配置 CSP。
无奈,只能自己去写一个简单的封装了。
export class GA {
constructor(ua, cid, debug = false) {
this.ua = ua;
this.cid = cid; // client id
this.gaApi = debug ? 'https://www.google-analytics.com/debug/collect' : 'https://www.google-analytics.com/collect';
this.version = '1';
}
ga(t, ...items) {
let payload = `v=${this.version}&tid=${this.ua}&cid=${this.cid}`;
let params = [];
switch (t) {
case 'pageview': // Pageview hit type
// dh -- Document hostname
// dp -- Page
// dt -- Title
params = ['dh', 'dp', 'dt'];
break;
case 'event':
// ec -- Event Category. Required
// ea -- Event Action. Required
// el -- Event label.
// ev -- Event value.
params = ['ec', 'ea', 'el', 'ev'];
}
if (params === []) return;
payload = `${payload}&t=${t}`;
items.forEach((v, i) => {
payload = `${payload}&${params[i]}=${encodeURIComponent(v)}`;
});
const request = new XMLHttpRequest();
request.open('POST', this.gaApi, true);
request.send(payload);
}
}
const uid = 'xxxx-xxxx-xxx-xxx';
const debug = false;
const gaID = 'UA-xxxxxx-x';
const gaObj = new GA(gaID, uid, debug);
function sendEvent(eventCategory, eventAction, eventLabel = '', eventValue = 1) {
if (store.getters.config.ga === false) return;
gaObj.ga('event', eventCategory, eventAction, eventLabel, eventValue);
}
// dh -- Document hostname, dp -- Page, dt -- Title
function sendPageview(dp, dh = '', dt = '') {
if (store.getters.config.ga === false) return;
gaObj.ga('pageview', dh, dp, dt);
}
这就是我根据官方文档简单写的封装。
这里面需要注意几个问题。
一个是正式环境的地址是 /collect 而测试地址是 /debug/collect。这个在之前的时候,没有注意到还有测试地址,所以绕了弯路,也没有发现提交的参数错误。
另外一个就是在 event 类型中,Event value 必须是整型。
还有个小技巧,就是调试的时候,可以切换到“实时”选项卡,在那下面可以看到发送到 /collect 的实时数据。
ET碎碎念,每周一,晚六点一刻更新,欢迎订阅
欢迎使用 SteemEditor 来编写文章,获取 @steemeditor.bot 的点赞!
感谢你的阅读,我是中文区见证人之一,欢迎通过 SteemConnect 来给我投票,或者打开 https://steemitwallet.com/~witnesses 页面,输入 ety001 进行投票。
中文区的见证人目前有:
支持一下他们(按字母顺序),一人可以有30票:
Thank you for reading. I'm a witness. I would really appreciate your witness vote! You can vote by SteemConnect. Or open https://steemitwallet.com/~witnesses page, input ety001 to vote.
Leave Google Analytics Api 使用 to:
Read more #cn posts
Best Posts From ETY001
We have not curated any of ety001's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From ETY001
- 解决CDN缓存301的问题
- Hivians, PLEASE BLOCK ME. Thank you!
- Hive chain coming is a SHAME TIME for Steem.
- 达则兼济天下
- 中国大陆地区第一台不稳定Steem全节点正式上线
- Code Server使用小技巧--禁用浏览器标签页关闭
- 区块链公司该如何保护自己的资产
- 我不站队Sun,但是我为个人资产站队
- 由《Vue.js: The Documentary》想起的一件往事
- 从帮助400+用户7天重温了9000+个书签说起
- 先问是不是,再问为什么
- 解决每次zip压缩后的md5不同的问题
- 这并不是远程工作的元年
- Google Analytics Api 使用
- 《爱情公寓》的剧终
- 最近的三两事
- 全新版本的Chrome扩展“温故知新”已通过审核上线
- 细节描写要适可而止
- 蓄势待发
- 用 js 控制 manifest.json 的 chrome_url_overrides