-
Notifications
You must be signed in to change notification settings - Fork 10
/
jquery.jsoncookie.js
72 lines (63 loc) · 1.63 KB
/
jquery.jsoncookie.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
/*!
* jQuery JSON Cookie
*
* Copyright 2011 appendTo LLC. (http://appendto.com/team)
* Dual licensed under the MIT or GPL licenses.
* http://appendto.com/open-source-licenses
*
* http://github.com/appendto/jquery-jsoncookie
*/
(function( $ ) {
var encode = encodeURIComponent,
decode = decodeURIComponent;
function now() {
return (new Date()).getTime();
}
$.cookie = function( key, value, options ) {
options = $.extend( {}, options );
var expires = options.expires,
result = value;
// get all cookies
if ( !key ) {
result = {};
$.each( document.cookie.split( "; " ), function( i, cookie ) {
if ( !cookie ) {
return;
}
var parts = cookie.split( "=" );
result[ decode( parts[ 0 ] ) ] = JSON.parse( decode( parts[ 1 ] ) );
});
return result;
}
// get/set a specific cookie
key = encode( key );
if ( value === undefined ) {
result = new RegExp( "(?:^|; )" + key + "=([^;]*)" ).exec( document.cookie );
return result && JSON.parse( decode( result[ 1 ] ) );
} else {
if ( value === null ) {
expires = -1;
}
if ( typeof expires === "number" ) {
expires = new Date( now() + expires );
}
document.cookie = [
key, "=", encode( JSON.stringify( value ) ),
expires ? "; expires=" + expires.toUTCString() : "",
options.path ? "; path=" + options.path : "",
options.domain ? "; domain=" + options.domain : "",
options.secure ? "; secure" : ""
].join( "" );
}
return result;
};
// support test
if ( $.support ) {
(function() {
var test = "jsoncookie" + now();
$.cookie( test, test );
$.support.cookie = $.cookie( test ) === test;
$.cookie( test, null );
}() );
}
}( jQuery ) );