From cefb0c399960553edae76f91f9fc5470a1c3bc04 Mon Sep 17 00:00:00 2001 From: Klaus Hartl Date: Wed, 30 Jan 2013 10:44:25 +0100 Subject: [PATCH] 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 #132. Closes #145. --- jquery.cookie.js | 4 +++- test/tests.js | 17 +++++++++++++++-- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/jquery.cookie.js b/jquery.cookie.js index 20fc964..06d5e21 100644 --- a/jquery.cookie.js +++ b/jquery.cookie.js @@ -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) { diff --git a/test/tests.js b/test/tests.js index 9c582aa..343becb 100644 --- a/test/tests.js +++ b/test/tests.js @@ -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 { @@ -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.