Skip to content

Commit 43ecd80

Browse files
committed
Allow strings to be saved and read while json == true. Also fixes removing such a cookie
while json == true. Closes js-cookie#195. Also see js-cookie#199.
1 parent bd134a7 commit 43ecd80

2 files changed

Lines changed: 29 additions & 17 deletions

File tree

‎jquery.cookie.js‎

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,27 +17,29 @@
1717

1818
var pluses = /\+/g;
1919

20-
function raw(s) {
21-
return s;
22-
}
23-
24-
function decoded(s) {
20+
function decode(s) {
21+
if (config.raw) {
22+
return s;
23+
}
2524
return decodeURIComponent(s.replace(pluses, ' '));
2625
}
2726

28-
function converted(s) {
27+
function decodeAndParse(s) {
2928
if (s.indexOf('"') === 0) {
30-
// This is a quoted cookie as according to RFC2068, unescape
29+
// This is a quoted cookie as according to RFC2068, unescape...
3130
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
3231
}
32+
33+
s = decode(s);
34+
3335
try {
3436
return config.json ? JSON.parse(s) : s;
35-
} catch(er) {}
37+
} catch(e) {}
3638
}
3739

3840
var config = $.cookie = function (key, value, options) {
3941

40-
// write
42+
// Write
4143
if (value !== undefined) {
4244
options = $.extend({}, config.defaults, options);
4345

@@ -59,22 +61,21 @@
5961
].join(''));
6062
}
6163

62-
// read
63-
var decode = config.raw ? raw : decoded;
64+
// Read
6465
var cookies = document.cookie.split('; ');
6566
var result = key ? undefined : {};
6667
for (var i = 0, l = cookies.length; i < l; i++) {
6768
var parts = cookies[i].split('=');
6869
var name = decode(parts.shift());
69-
var cookie = decode(parts.join('='));
70+
var cookie = parts.join('=');
7071

7172
if (key && key === name) {
72-
result = converted(cookie);
73+
result = decodeAndParse(cookie);
7374
break;
7475
}
7576

7677
if (!key) {
77-
result[name] = converted(cookie);
78+
result[name] = decodeAndParse(cookie);
7879
}
7980
}
8081

‎test/tests.js‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,14 +82,25 @@ test('not existing with json = true', function () {
8282
}
8383
});
8484

85-
test('invalid JSON string with json = true', function () {
85+
test('string with json = true', function () {
8686
expect(1);
8787

88-
8988
if ('JSON' in window) {
9089
$.cookie.json = true;
9190
$.cookie('c', 'v');
92-
strictEqual($.cookie('c'), undefined, "won't throw exception, returns undefined");
91+
strictEqual($.cookie('c'), 'v', 'should return value');
92+
} else {
93+
ok(true);
94+
}
95+
});
96+
97+
test('invalid JSON string with json = true', function () {
98+
expect(1);
99+
100+
if ('JSON' in window) {
101+
$.cookie('c', 'v');
102+
$.cookie.json = true;
103+
strictEqual($.cookie('c'), undefined, "won't throw exception, returns unquoted string");
93104
} else {
94105
ok(true);
95106
}

0 commit comments

Comments
 (0)