Skip to content

Commit 81dd6a1

Browse files
committed
Handle decoding error gracefully upon reading, return undefined. Closes #215.
1 parent a1e99ef commit 81dd6a1

3 files changed

Lines changed: 25 additions & 3 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ HEAD
1212
- Renamed bower package definition (component.json -> bower.json) for usage
1313
with up-to-date bower.
1414

15+
- Badly encoded cookies no longer throw exception upon reading but do return
16+
undefined (similar to how we handle JSON parse errors with json = true).
17+
1518
1.3.1
1619
-----
1720
- Fixed issue where it was no longer possible to check for an arbitrary cookie,

‎jquery.cookie.js‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,10 @@
2121
if (config.raw) {
2222
return s;
2323
}
24-
return decodeURIComponent(s.replace(pluses, ' '));
24+
try {
25+
// If we can't decode the cookie, ignore it, it's unusable.
26+
return decodeURIComponent(s.replace(pluses, ' '));
27+
} catch(e) {}
2528
}
2629

2730
function decodeAndParse(s) {
@@ -33,6 +36,7 @@
3336
s = decode(s);
3437

3538
try {
39+
// If we can't parse the cookie, ignore it, it's unusable.
3640
return config.json ? JSON.parse(s) : s;
3741
} catch(e) {}
3842
}
@@ -80,8 +84,9 @@
8084
break;
8185
}
8286

83-
if (!key) {
84-
result[name] = decodeAndParse(cookie);
87+
// Prevent storing a cookie that we couldn't decode.
88+
if (!key && (cookie = decodeAndParse(cookie)) !== undefined) {
89+
result[name] = cookie;
8590
}
8691
}
8792

‎test/tests.js‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,13 @@ test('invalid JSON string with json = true', function () {
106106
}
107107
});
108108

109+
test('invalid URL encoding', function () {
110+
expect(1);
111+
document.cookie = 'bad=foo%';
112+
strictEqual($.cookie('bad'), undefined, "won't throw exception, returns undefined");
113+
document.cookie = 'bad=foo'; // Allow to be deleted...
114+
});
115+
109116
asyncTest('malformed cookie value in IE (#88, #117)', function() {
110117
expect(1);
111118
// Sandbox in an iframe so that we can poke around with document.cookie.
@@ -140,6 +147,13 @@ test('Call to read all with json: true', function() {
140147
deepEqual($.cookie(), { c: { foo: 'bar' } }, 'returns JSON parsed cookies');
141148
});
142149

150+
test('Call to read all with a badly encoded cookie', function() {
151+
expect(1);
152+
document.cookie = 'bad=foo%';
153+
document.cookie = 'good=foo';
154+
deepEqual($.cookie(), { good: 'foo' }, 'returns object containing all decodable cookies');
155+
});
156+
143157

144158
module('write', lifecycle);
145159

0 commit comments

Comments
 (0)