Skip to content

Commit

Permalink
When attempting to read a cookie with json=true and the JSON string i…
Browse files Browse the repository at this point in the history
…s 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 carhartl#132. Closes carhartl#145.
  • Loading branch information
carhartl committed Jan 30, 2013
1 parent cd21803 commit cefb0c3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
4 changes: 3 additions & 1 deletion jquery.cookie.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@
// This is a quoted cookie as according to RFC2068, unescape
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
return config.json ? JSON.parse(s) : s;
try {
return config.json ? JSON.parse(s) : s;
} catch(er) {}
}

var config = $.cookie = function (key, value, options) {
Expand Down
17 changes: 15 additions & 2 deletions test/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,9 @@ test('raw = true', function () {

test('json = true', function () {
expect(1);
$.cookie.json = true;

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

test('not existing with json = true', function () {
expect(1);
$.cookie.json = true;

if ('JSON' in window) {
$.cookie.json = true;
strictEqual($.cookie('whatever'), undefined, "won't throw exception");
} else {
ok(true);
}
});

test('invalid JSON string with json = true', function () {
expect(1);


if ('JSON' in window) {
$.cookie.json = true;
$.cookie('c', 'v');
strictEqual($.cookie('c'), undefined, "won't throw exception, returns undefined");
} else {
ok(true);
}
});

asyncTest('malformed cookie value in IE (#88, #117)', function() {
expect(1);
// Sandbox in an iframe so that we can poke around with document.cookie.
Expand Down

0 comments on commit cefb0c3

Please sign in to comment.