-
Notifications
You must be signed in to change notification settings - Fork 1
/
simpleCookie.js
66 lines (65 loc) · 2.36 KB
/
simpleCookie.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
/* simpleCookie.js
*
* A small javascript utility to make handling cookies simple
*
* Author: Tim Evko
* https://twitter.com/tevko
* https://timevko.website
* https://github.com/tevko/simpleCookie
* License: MIT
*
*/
;(function() {
'use strict';
window._smplCke = {
/**
* returns true if a cookie exists
* @param {string} name - the name of the cookie
* @return {Boolean} - returns true if the cookie exists
*/
is: function(name) {
return document.cookie.indexOf(name + '=') > -1;
},
/**
* returns the value of a cookie as an object
* @param {string} name - the name of the cookie to be returned
* @return {object} - a JS object representation of the cookie
*/
get: function(name) {
// if the cookie value is a normal string, just return it
try {
var jsonString = decodeURIComponent(document.cookie.split(name + '=')[1].split(';')[0]);
return JSON.parse(jsonString);
} catch(e) {
return document.cookie.split(name + '=')[1].split(';')[0];
}
},
/**
* sets a cookie
* @param {string} name - the name of the cookie
* @param {string | object} value - the body of the cookie
* @param OPTIONAL {date string} expiration - a valid UTC date string "Thu, 18 Dec 2013 12:00:00 UTC" DEFAULT - Session
* @param OPTIONAL {string} path - a URL path where the cookie should exist DEFAULT - '/'
*/
set: function(name, value, expiration, path, httpOnly) {
if (typeof path === 'undefined') {
path = '/';
}
if (typeof value === 'object') {
value = JSON.stringify(value);
}
if (typeof expiration === 'undefined') {
document.cookie = name + '=' + value + '; path=' + path;
} else {
document.cookie = name + '=' + value + ';expires=' + expiration + '; path=' + path;
}
},
/**
* deletes a cookie
* @param {string} name - the name of the cookie
*/
del: function(name) {
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
}
})();