Skip to content

Commit e36ddd2

Browse files
Should not throw an exception for a third party malformed cookie
If there is a malformed cookie that cannot be decoded using the default decoding mechanism, it should be ignored and fail to read that single cookie. It should not prevent an unrelated cookie to be retrieved. Closes js-cookiegh-62.
1 parent 76932e3 commit e36ddd2

File tree

2 files changed

+25
-13
lines changed

2 files changed

+25
-13
lines changed

src/js.cookie.js

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -93,22 +93,24 @@
9393
cookie = cookie.slice(1, -1);
9494
}
9595

96-
cookie = converter && converter(cookie, name) || cookie.replace(rdecode, decodeURIComponent);
96+
try {
97+
cookie = converter && converter(cookie, name) || cookie.replace(rdecode, decodeURIComponent);
9798

98-
if (this.json) {
99-
try {
100-
cookie = JSON.parse(cookie);
101-
} catch (e) {}
102-
}
99+
if (this.json) {
100+
try {
101+
cookie = JSON.parse(cookie);
102+
} catch (e) {}
103+
}
103104

104-
if (key === name) {
105-
result = cookie;
106-
break;
107-
}
105+
if (key === name) {
106+
result = cookie;
107+
break;
108+
}
108109

109-
if (!key) {
110-
result[name] = cookie;
111-
}
110+
if (!key) {
111+
result[name] = cookie;
112+
}
113+
} catch (e) {}
112114
}
113115

114116
return result;

test/tests.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,16 @@ QUnit.test('RFC 6265 - reading cookie-octet enclosed in DQUOTE', function (asser
7979
assert.strictEqual(Cookies.get('c'), 'v', 'should simply ignore quoted strings');
8080
});
8181

82+
// github.com/js-cookie/js-cookie/pull/62
83+
QUnit.test('Call to read cookie when there is another unrelated cookie with malformed encoding in the value', function (assert) {
84+
assert.expect(2);
85+
document.cookie = 'invalid=%A1';
86+
document.cookie = 'c=v';
87+
assert.strictEqual(Cookies.get('c'), 'v', 'should not throw a URI malformed exception when retrieving a single cookie');
88+
assert.deepEqual(Cookies.get(), { c: 'v' }, 'should not throw a URI malformed exception when retrieving all cookies');
89+
Cookies.withConverter(unescape).remove('invalid');
90+
});
91+
8292
QUnit.module('write', lifecycle);
8393

8494
QUnit.test('String primitive', function (assert) {

0 commit comments

Comments
 (0)