-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcookie.js
More file actions
47 lines (43 loc) · 1.61 KB
/
cookie.js
File metadata and controls
47 lines (43 loc) · 1.61 KB
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
// Fix: Allow to exist with or without jQuery
if (typeof $ === 'undefined' || $ === null || typeof $ !== 'object') {
var $ = {};
}
// Source: https://stackoverflow.com/a/48521179/3894752
// Note: This will return false on localhost in Chrome https://stackoverflow.com/a/8225269
$.areCookiesEnabled = function() {
try {
// Create cookie
document.cookie = 'cookietest=1';
const cookiesEnabled = document.cookie.indexOf('cookietest=') !== -1;
// Delete cookie
document.cookie = 'cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT';
return cookiesEnabled;
} catch (e) {
return false;
}
}
// Source: https://gist.githubusercontent.com/bronson/6707533/raw/7317b0e0d204d00d3b01d06f9f18a09ae4ee6f4e/cookie.js
// cookie.js
//
// Usage:
// $.cookie('mine', 'data', 5*60*1000) -- write data to cookie named mine that lasts for five minutes
// $.cookie('mine') -- read the cookie that was just set, function result will be 'data'
// $.cookie('mine', '', -1) -- delete the cookie
$.cookie = function(name, value, ms) {
if (arguments.length < 2) {
// read cookie
const cookies = document.cookie.split(';');
for (const cookie of cookies) {
const c = cookie.replace(/^\s+/, '');
if (c.indexOf(name + '=') === 0) {
return decodeURIComponent(c.substring(name.length + 1).split('+').join(' '));
}
}
return null;
}
// write cookie
const date = new Date();
date.setTime(date.getTime() + ms);
const expires = ms ? `;expires=${date.toUTCString()}` : '';
document.cookie = `${name}=${encodeURIComponent(value)}${expires};path=/`;
}