Skip to content

Commit 64eb7b7

Browse files
committed
Implemented conversion function as optional last argument for reading. Also see js-cookie#151.
Along with it fixed that certain decoding and sanitizing should not happen for a cookie's key.
1 parent 43660d4 commit 64eb7b7

6 files changed

Lines changed: 76 additions & 20 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,15 @@ HEAD
1515
- Badly encoded cookies no longer throw exception upon reading but do return
1616
undefined (similar to how we handle JSON parse errors with json = true).
1717

18+
- Added conversion function as optional last argument for reading,
19+
so that values can be changed to a different representation easily on the fly.
20+
Useful for parsing numbers for instance:
21+
22+
```javascript
23+
$.cookie('foo', '42');
24+
$.cookie('foo', Number); // => 42
25+
```
26+
1827
1.3.1
1928
-----
2029
- Fixed issue where it was no longer possible to check for an arbitrary cookie,

‎README.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,27 @@ Define the domain where the cookie is valid. Default: domain of page where the c
9898

9999
If true, the cookie transmission requires a secure protocol (https). Default: `false`.
100100

101+
## Converters
102+
103+
Provide a conversion function as optional last argument for reading, in order to change the cookie's value
104+
to a different representation on the fly.
105+
106+
Example for parsing a value into a number:
107+
108+
```javascript
109+
$.cookie('foo', '42');
110+
$.cookie('foo', Number); // => 42
111+
```
112+
113+
Dealing with cookies that have been encoded using `escape` (3rd party cookies):
114+
115+
```javascript
116+
$.cookie.raw = true;
117+
$.cookie('foo', unescape);
118+
```
119+
120+
You can pass an arbitrary conversion function.
121+
101122
## Contributing
102123

103124
Check out the [Contributing Guidelines](CONTRIBUTING.md)

‎bower.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"./jquery.cookie.js"
66
],
77
"dependencies": {
8-
"jquery": ">=1.0"
8+
"jquery": ">=1.2"
99
},
1010
"ignore": [
1111
"test",

‎cookie.jquery.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
}
2525
],
2626
"dependencies": {
27-
"jquery": ">=1.0"
27+
"jquery": ">=1.2"
2828
},
2929
"bugs": "https://github.com/carhartl/jquery-cookie/issues",
3030
"homepage": "https://github.com/carhartl/jquery-cookie",

‎jquery.cookie.js‎

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -17,47 +17,56 @@
1717

1818
var pluses = /\+/g;
1919

20+
function encode(s) {
21+
return config.raw ? s : encodeURIComponent(s);
22+
}
23+
2024
function decode(s) {
21-
if (config.raw) {
22-
return s;
23-
}
24-
try {
25-
// If we can't decode the cookie, ignore it, it's unusable.
26-
return decodeURIComponent(s.replace(pluses, ' '));
27-
} catch(e) {}
25+
return config.raw ? s : decodeURIComponent(s);
26+
}
27+
28+
function stringifyCookieValue(value) {
29+
return encode(config.json ? JSON.stringify(value) : String(value));
2830
}
2931

30-
function decodeAndParse(s) {
32+
function parseCookieValue(s) {
3133
if (s.indexOf('"') === 0) {
3234
// This is a quoted cookie as according to RFC2068, unescape...
3335
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
3436
}
3537

36-
s = decode(s);
38+
try {
39+
// Replace server-side written pluses with spaces.
40+
// If we can't decode the cookie, ignore it, it's unusable.
41+
s = decodeURIComponent(s.replace(pluses, ' '));
42+
} catch(e) {
43+
return;
44+
}
3745

3846
try {
3947
// If we can't parse the cookie, ignore it, it's unusable.
4048
return config.json ? JSON.parse(s) : s;
4149
} catch(e) {}
4250
}
4351

52+
function read(s, converter) {
53+
var value = config.raw ? s : parseCookieValue(s);
54+
return $.isFunction(converter) ? converter(value) : value;
55+
}
56+
4457
var config = $.cookie = function (key, value, options) {
4558

4659
// Write
47-
if (value !== undefined) {
60+
if (value !== undefined && !$.isFunction(value)) {
4861
options = $.extend({}, config.defaults, options);
4962

5063
if (typeof options.expires === 'number') {
5164
var days = options.expires, t = options.expires = new Date();
5265
t.setDate(t.getDate() + days);
5366
}
5467

55-
value = config.json ? JSON.stringify(value) : String(value);
56-
5768
return (document.cookie = [
58-
config.raw ? key : encodeURIComponent(key),
59-
'=',
60-
config.raw ? value : encodeURIComponent(value),
69+
encode(key), '=', stringifyCookieValue(value),
6170
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
6271
options.path ? '; path=' + options.path : '',
6372
options.domain ? '; domain=' + options.domain : '',
@@ -80,12 +89,13 @@
8089
var cookie = parts.join('=');
8190

8291
if (key && key === name) {
83-
result = decodeAndParse(cookie);
92+
// If second argument (value) is a function it's a converter...
93+
result = read(cookie, value);
8494
break;
8595
}
8696

8797
// Prevent storing a cookie that we couldn't decode.
88-
if (!key && (cookie = decodeAndParse(cookie)) !== undefined) {
98+
if (!key && (cookie = read(cookie)) !== undefined) {
8999
result[name] = cookie;
90100
}
91101
}

‎test/tests.js‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ test('json = true', function () {
6565
if ('JSON' in window) {
6666
$.cookie.json = true;
6767
$.cookie('c', { foo: 'bar' });
68-
deepEqual($.cookie('c'), { foo: 'bar'}, 'should parse JSON');
68+
deepEqual($.cookie('c'), { foo: 'bar' }, 'should parse JSON');
6969
} else {
7070
ok(true);
7171
}
@@ -285,3 +285,19 @@ test('[] used in name', function () {
285285
$.removeCookie('c[1]');
286286
strictEqual(document.cookie, '', 'delete the cookie');
287287
});
288+
289+
290+
module('conversion', lifecycle);
291+
292+
test('read converter', function() {
293+
expect(1);
294+
$.cookie('c', '1');
295+
strictEqual($.cookie('c', Number), 1, 'converts read value');
296+
});
297+
298+
test('read converter with raw = true', function() {
299+
expect(1);
300+
$.cookie.raw = true;
301+
$.cookie('c', '1');
302+
strictEqual($.cookie('c', Number), 1, 'does not decode, but converts read value');
303+
});

0 commit comments

Comments
 (0)