Skip to content

Commit cefb0c3

Browse files
committed
When attempting to read a cookie with json=true and the JSON string is invalid,
no longer throw a SyntaxError, but simply return undefined as if the cookie doesn't exist. Such cookie isn't usable as JSON cookie, thus we're treating it as not existing. Closes js-cookie#132. Closes js-cookie#145.
1 parent cd21803 commit cefb0c3

2 files changed

Lines changed: 18 additions & 3 deletions

File tree

‎jquery.cookie.js‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,9 @@
3030
// This is a quoted cookie as according to RFC2068, unescape
3131
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
3232
}
33-
return config.json ? JSON.parse(s) : s;
33+
try {
34+
return config.json ? JSON.parse(s) : s;
35+
} catch(er) {}
3436
}
3537

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

‎test/tests.js‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,9 @@ test('raw = true', function () {
6161

6262
test('json = true', function () {
6363
expect(1);
64-
$.cookie.json = true;
6564

6665
if ('JSON' in window) {
66+
$.cookie.json = true;
6767
$.cookie('c', { foo: 'bar' });
6868
deepEqual($.cookie('c'), { foo: 'bar'}, 'should parse JSON');
6969
} else {
@@ -73,15 +73,28 @@ test('json = true', function () {
7373

7474
test('not existing with json = true', function () {
7575
expect(1);
76-
$.cookie.json = true;
7776

7877
if ('JSON' in window) {
78+
$.cookie.json = true;
7979
strictEqual($.cookie('whatever'), undefined, "won't throw exception");
8080
} else {
8181
ok(true);
8282
}
8383
});
8484

85+
test('invalid JSON string with json = true', function () {
86+
expect(1);
87+
88+
89+
if ('JSON' in window) {
90+
$.cookie.json = true;
91+
$.cookie('c', 'v');
92+
strictEqual($.cookie('c'), undefined, "won't throw exception, returns undefined");
93+
} else {
94+
ok(true);
95+
}
96+
});
97+
8598
asyncTest('malformed cookie value in IE (#88, #117)', function() {
8699
expect(1);
87100
// Sandbox in an iframe so that we can poke around with document.cookie.

0 commit comments

Comments
 (0)