Skip to content

Commit 4150b5e

Browse files
Merge pull request #8 from js-cookie/RFC-6265
RFC 6265 compliance
2 parents 19e479c + bfa572a commit 4150b5e

3 files changed

Lines changed: 249 additions & 106 deletions

File tree

‎README.md‎

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -45,14 +45,14 @@ Cookies.set('name', 'value', { expires: 7, path: '/' });
4545
Read cookie:
4646

4747
```javascript
48-
Cookies.get('name'); // => "value"
48+
Cookies.get('name'); // => 'value'
4949
Cookies.get('nothing'); // => undefined
5050
```
5151

5252
Read all available cookies:
5353

5454
```javascript
55-
Cookies.get(); // => { "name": "value" }
55+
Cookies.get(); // => { name: 'value' }
5656
```
5757

5858
Delete cookie:
@@ -72,16 +72,35 @@ Cookies.remove('name', { path: '/' }); // => true
7272

7373
*Note: when deleting a cookie, you must pass the exact same path, domain and secure options that were used to set the cookie, unless you're relying on the default options that is.*
7474

75-
## Configuration
75+
## JSON
7676

77-
### json
77+
js-cookie provides automatic JSON storage for cookies.
7878

79-
Turn on automatic storage of JSON objects passed as the cookie value. Assumes `JSON.stringify` and `JSON.parse`:
79+
When creating a cookie you can pass an Array or Object Literal instead of a string in the value. If you do so, js-cookie store the string representation of the object according to the `JSON.stringify` api (if available):
8080

8181
```javascript
82-
Cookies.json = true;
82+
Cookies.set('name', { foo: 'bar' });
8383
```
8484

85+
When reading a cookie with the default `Cookies.get()` api, you receive the stringified representation stored in the cookie:
86+
87+
```javascript
88+
Cookies.get('name'); // => '{"foo":"bar"}'
89+
```
90+
91+
When reading a cookie with the `Cookies.getJSON()` api, you receive the parsed representation of the string stored in the cookie according to the `JSON.stringify` api (if available):
92+
93+
```javascript
94+
Cookies.getJSON('name'); // => { foo: 'bar' }
95+
```
96+
97+
## RFC 6265
98+
99+
This project assumes [RFC 6265](http://tools.ietf.org/html/rfc6265#section-4.1.1) as a reference for everything. That said, some custom rules are applied in order to provide robustness and cross-browser compatibility.
100+
101+
### Encoding
102+
All special characters that are not allowed in the cookie-value or cookie-name in at least one supported browser are encoded/decoded with each UTF-8 Hex equivalent. Special characters that consistently work among all supported browsers are not encoded/decoded this way.
103+
85104
## Cookie Options
86105

87106
Cookie attributes can be set globally by setting properties of the `Cookies.defaults` object or individually for each call to `Cookies.set()` by passing a plain object to the options argument. Per-call options override the default options.
@@ -123,11 +142,13 @@ If true, the cookie transmission requires a secure protocol (https). Default: `f
123142
Provide a conversion function as optional last argument for reading, in order to change the cookie's value
124143
to a different representation on the fly.
125144

126-
Example for parsing a value into a number:
145+
Example for parsing the value from a cookie generated with PHP's `setcookie()` method:
127146

128147
```javascript
129-
Cookies.set('foo', '42');
130-
Cookies.get('foo', Number); // => 42
148+
// 'cookie+with+space' => 'cookie with space'
149+
Cookies.get('foo', function (value) {
150+
return value.replace(/\+/g, ' ');
151+
});
131152
```
132153

133154
Dealing with cookies that have been encoded using `escape` (3rd party cookies):
@@ -136,8 +157,6 @@ Dealing with cookies that have been encoded using `escape` (3rd party cookies):
136157
Cookies.get('foo', unescape);
137158
```
138159

139-
You can pass an arbitrary conversion function.
140-
141160
## Contributing
142161

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

‎src/js.cookie.js‎

Lines changed: 62 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -17,35 +17,64 @@
1717
window.Cookies = factory();
1818
}
1919
}(function () {
20-
function encode(s) {
21-
return s
22-
.replace(/"/g, '%22');
20+
var unallowedChars = {
21+
';': '%3B',
22+
',': '%2C',
23+
'"': '%22'
24+
};
25+
var unallowedCharsInName = extend(unallowedChars, {
26+
'=': '%3D',
27+
'\t': '%09'
28+
});
29+
var unallowedCharsInValue = extend(unallowedChars, {
30+
' ': '%20'
31+
});
32+
33+
function encode (value, charmap) {
34+
for (var character in charmap) {
35+
value = value
36+
.replace(new RegExp(character, 'g'), charmap[character]);
37+
}
38+
return value;
39+
}
40+
41+
function decode (value, charmap) {
42+
for (var character in charmap) {
43+
value = value
44+
.replace(new RegExp(charmap[character], 'g'), character);
45+
}
46+
return value;
2347
}
2448

25-
function decode(s) {
26-
return s
27-
.replace(/%22/g, '"');
49+
function processWrite (value) {
50+
var stringified;
51+
try {
52+
stringified = JSON.stringify(value);
53+
if (/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/.test(stringified)) {
54+
value = stringified;
55+
}
56+
} catch(e) {}
57+
return encode(String(value), unallowedCharsInValue);
2858
}
2959

30-
function parseCookieValue(value) {
60+
function processRead (value, converter, json) {
3161
if (value.indexOf('"') === 0) {
3262
// This is a quoted cookie as according to RFC2068, unescape...
3363
value = value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
3464
}
3565

36-
value = decode(value);
66+
value = decode(value, unallowedCharsInValue);
3767

38-
try {
39-
return api.json ? JSON.parse(value) : value;
40-
} catch(e) {}
41-
}
68+
if (json) {
69+
try {
70+
value = JSON.parse(value);
71+
} catch(e) {}
72+
}
4273

43-
function read(s, converter) {
44-
var value = parseCookieValue(s);
4574
return isFunction(converter) ? converter(value) : value;
4675
}
4776

48-
function extend() {
77+
function extend () {
4978
var key, options;
5079
var i = 0;
5180
var result = {};
@@ -58,15 +87,21 @@
5887
return result;
5988
}
6089

61-
function isFunction(obj) {
90+
function isFunction (obj) {
6291
return Object.prototype.toString.call(obj) === '[object Function]';
6392
}
6493

6594
var api = function (key, value, options) {
95+
var converter;
96+
97+
if (isFunction(value)) {
98+
converter = value;
99+
value = undefined;
100+
}
66101

67102
// Write
68103

69-
if (arguments.length > 1 && !isFunction(value)) {
104+
if (arguments.length > 1 && !converter) {
70105
options = extend(api.defaults, options);
71106

72107
if (typeof options.expires === 'number') {
@@ -75,7 +110,7 @@
75110
}
76111

77112
return (document.cookie = [
78-
key, '=', encode(api.json ? JSON.stringify(value) : String(value)),
113+
encode(key, unallowedCharsInName), '=', processWrite(value),
79114
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
80115
options.path ? '; path=' + options.path : '',
81116
options.domain ? '; domain=' + options.domain : '',
@@ -95,25 +130,28 @@
95130

96131
for (; i < l; i++) {
97132
var parts = cookies[i].split('='),
98-
name = parts.shift(),
133+
name = decode(parts.shift(), unallowedCharsInName),
99134
cookie = parts.join('=');
100135

101136
if (key === name) {
102-
// If second argument (value) is a function it's a converter...
103-
result = read(cookie, value);
137+
result = processRead(cookie, converter, this.json);
104138
break;
105139
}
106140

107-
// Prevent storing a cookie that we couldn't decode.
108-
if (!key && (cookie = read(cookie)) !== undefined) {
109-
result[name] = cookie;
141+
if (!key) {
142+
result[name] = processRead(cookie, converter, this.json);
110143
}
111144
}
112145

113146
return result;
114147
};
115148

116149
api.get = api.set = api;
150+
api.getJSON = function() {
151+
return api.get.apply({
152+
json: true
153+
}, [].slice.call(arguments));
154+
};
117155
api.defaults = {};
118156

119157
api.remove = function (key, options) {

0 commit comments

Comments
 (0)