-
Notifications
You must be signed in to change notification settings - Fork 133
/
Copy pathcookie.js
139 lines (110 loc) · 2.58 KB
/
cookie.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
/*
* Cookie data
*/
import Base64 from './base64';
import utils from './utils';
import getLocation from './get-location';
import baseCookie from './base-cookie';
var _options = {
expirationDays: undefined,
domain: undefined
};
var reset = function() {
_options = {
expirationDays: undefined,
domain: undefined
};
};
const getHost = (url) => {
const a = document.createElement('a');
a.href = url;
return a.hostname || location.hostname;
};
const topDomain = (url) => {
const host = getHost(url);
const parts = host.split('.');
const last = parts[parts.length - 1];
const levels = [];
if (parts.length === 4 && last === parseInt(last, 10)) {
return levels;
}
if (parts.length <= 1) {
return levels;
}
for (let i = parts.length - 2; i >= 0; --i) {
levels.push(parts.slice(i).join('.'));
}
for (let i = 0; i < levels.length; ++i) {
const cname = '__tld_test__';
const domain = levels[i];
const opts = { domain: domain };
baseCookie.set(cname, 1, opts);
if (baseCookie.get(cname)) {
baseCookie.set(cname, null, opts);
return domain;
}
}
return '';
};
var options = function(opts) {
if (arguments.length === 0) {
return _options;
}
opts = opts || {};
_options.expirationDays = opts.expirationDays;
_options.secure = opts.secure;
var domain = (opts.domain !== undefined) ? opts.domain : topDomain(getLocation().href);
var token = Math.random();
_options.domain = domain;
set('amplitude_test', token);
var stored = get('amplitude_test');
if (!stored || stored !== token) {
domain = null;
}
remove('amplitude_test');
_options.domain = domain;
return _options;
};
var _domainSpecific = function(name) {
// differentiate between cookies on different domains
var suffix = '';
if (_options.domain) {
suffix = _options.domain.charAt(0) === '.' ? _options.domain.substring(1) : _options.domain;
}
return name + suffix;
};
var get = function(name) {
var nameEq = _domainSpecific(name) + '=';
const value = baseCookie.get(nameEq);
try {
if (value) {
return JSON.parse(Base64.decode(value));
}
} catch (e) {
return null;
}
return null;
};
var set = function(name, value) {
try {
baseCookie.set(_domainSpecific(name), Base64.encode(JSON.stringify(value)), _options);
return true;
} catch (e) {
return false;
}
};
var remove = function(name) {
try {
baseCookie.set(_domainSpecific(name), null, _options);
return true;
} catch (e) {
return false;
}
};
export default {
reset,
options,
get,
set,
remove
};