-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrack.js
68 lines (60 loc) · 1.76 KB
/
track.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import qs from 'querystring';
import { request } from './request';
import env from './env';
const debug = require('debug')('track');
const getLoginUserId = cached(async() => {
// 打点取用户id不管环境,直接取线上的
const { data } = await request({
scope: 'member',
url: '/account/query',
env: 'production'
});
return data && data.user && data.user.id;
});
export default async function track({ type, id, data }) {
debug('track: [%s] %s', type, id);
const url = await getTrackUrl({ type, id, data, ext: '.gif' });
const img = new Image();
img.src = url;
}
export async function trackSync({ type, id, data }) {
debug('track sync: [%s] %s', type, id);
const url = await getTrackUrl({ type, id, data });
const xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
xhr.send();
}
async function getTrackUrl({ type, id, data, ext = '' }) {
type = type || 'click';
const userId = await getLoginUserId();
if (env === 'development') {
type = 'test_' + type;
}
const url = window.location.href.replace(/#.*$/, ''); // remove hash
const query = {
APIVersion: '0.6.0', // 保留字段,必选
url,
__topic__: userId || '',
__userAgent__: window.navigator.userAgent,
type,
id: id || '',
data: JSON.stringify(data || {}),
_t: Date.now()
};
const trackUrl =
'https://learninqgt.cn-hangzhou.log.aliyuncs.com/logstores/document/track';
return `${trackUrl}${ext}?${qs.stringify(query)}`;
}
function cached(fn) {
let called = false;
let result = null;
return async function() {
if (called) {
return result;
}
called = true;
result = await fn.apply(this, arguments);
return result;
};
}