-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathanalytics.js
122 lines (63 loc) · 2.32 KB
/
analytics.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
const getPage = () => window.location.pathname;
const getUserAgent = () => navigator.userAgent;
const getIP = async () => {
let resp = await fetch("https://freegeoip.app/json/");
let json = await resp.json();
let {ip = "N/A", longitude, latitude, country_name} = json;
return {ip, longitude, latitude, country_name};
};
const setCookie = (key,value,days=1) => {
var expires = "";
if (days) {
const date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = date.toUTCString();
}
document.cookie = key + "=" + (value || "") + "; expires=" + expires + "; path=/";
};
const getCookie = (name) => {
const nameVal = name;
const entries = document.cookie.split(';');
for(let id = 0; id < entries.length; id++) {
let [entryName, value] = entries[id].split("=");
if(entryName == nameVal) return value;
}
return null;
};
const parseOrigin = () => getCookie("origin");
const setOrigin = () => setCookie("origin", window.location.pathname, 365);
const readOrigin = () => {
const origin = parseOrigin();
if(!origin) {
setOrigin();
return window.location.pathname;
} else {
return origin;
}
};
const readReferral = () => new URLSearchParams(window.location.search).get("r") || document.referrer;
const logSession = async () => {
const page = getPage();
const ip = await getIP();
const origin = readOrigin();
const referral = readReferral();
const logData = {page, ...ip, origin, ref: referral, time: new Date().toISOString()};
let resp = await fetch("/api/populate", {method: "post", body: JSON.stringify(logData)});
let respJSON = await resp.json();
console.log(respJSON);
let count = respJSON.data.count;
let views = document.querySelector("#distribution-count .counter");
if(views) {
views.textContent = (count + 1) + "";
}
};
const logClick = async (id) => {
let link = document.querySelector(id);
const ip = await getIP();
if(!link) { console.error("DOM element doesn't exist", id); };
link.addEventListener("click", e => {
fetch("/.netlify/functions/clickstream", {method: "post", body: JSON.stringify({page: getPage(), userAgent: getUserAgent(), linkId: id, time: new Date().toISOString(), ip})});
})
}
logSession();
export { logClick };