-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutm.js
106 lines (95 loc) · 2.65 KB
/
utm.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
function getCookie(name) {
if (
(match = document.cookie.match(RegExp(encodeURIComponent(name) + '=([^;]+)')))
) {
return decodeURIComponent(match[1]);
}
}
function setCookie(name, value, domain, path, lifespanInMs) {
if (lifespanInMs) {
var expiryDate = new Date();
expiryDate.setTime(expiryDate.getTime() + 24 * lifespanInMs * 36e5);
var expiresStatement = '; expires=' + expiryDate.toGMTString();
} else {
expiresStatement = '';
}
document.cookie =
encodeURIComponent(name) +
'=' +
encodeURIComponent(value) +
expiresStatement +
'; domain=' +
domain +
'; path=' +
path;
}
function deleteCookie(name, domain, path) {
document.cookie =
encodeURIComponent(name) +
'=' +
(domain ? ';domain=' + domain : '') +
(path ? ';path=' + path : '') +
';expires=Thu, 01 Jan 1970 00:00:01 GMT';
}
function setTLDCookie(name, value, lifespanInMs) {
setCookie(
name,
value,
window.location.hostname.split('.').slice(-2).join('.'),
'/',
lifespanInMs,
);
}
function deleteTLDCookie(name) {
deleteCookie(name, window.location.hostname.split('.').slice(-2).join('.'), '/');
}
function getUrlParam(name) {
var matches = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return matches && decodeURIComponent(matches[1].replace(/\+/g, ' '));
}
var utm_names = [
'utm_campaign',
'utm_source',
'utm_medium',
'utm_content',
'utm_term',
'gclid',
'cid',
'msclkid',
'fbclid',
'li_fat_id',
];
function getLastTouchCookie(name) {
return getCookie(name) || getCookie(name + '_last');
}
function deleteLastTouchCookie(name) {
deleteTLDCookie(name);
deleteTLDCookie(name + '_last');
}
$(document).ready(function () {
if (!utm_names.some(getUrlParam)) {
return;
}
var firstTouchCookies = utm_names.map((suffixlessName) => getCookie(suffixlessName + '_first')).filter(cookie => Boolean(cookie));
if (firstTouchCookies.length === 0) {
utm_names.forEach(function (suffixlessName) {
var firstTouchCookieName = suffixlessName + '_first';
var urlParamValue = getUrlParam(suffixlessName);
if (urlParamValue) {
setTLDCookie(firstTouchCookieName, urlParamValue, 36500);
}
});
}
utm_names.forEach(function (suffixlessName) {
var urlParamValue = getUrlParam(suffixlessName);
if (urlParamValue) {
var lastTouchCookie = getLastTouchCookie(suffixlessName);
if (lastTouchCookie && (lastTouchCookie !== urlParamValue)) {
deleteLastTouchCookie(suffixlessName);
}
setTLDCookie(suffixlessName + '_last', urlParamValue, 36500);
} else {
deleteLastTouchCookie(suffixlessName);
}
});
});