Skip to content

Commit bfa572a

Browse files
Merge pull request #9 from js-cookie/remove-json
Remove json config
2 parents 84d838b + a52398d commit bfa572a

3 files changed

Lines changed: 146 additions & 104 deletions

File tree

‎README.md‎

Lines changed: 27 additions & 15 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,23 +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-
## RFC 6265
75+
## JSON
7676

77-
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.
77+
js-cookie provides automatic JSON storage for cookies.
7878

79-
### Encoding
80-
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.
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):
8180

82-
## Configuration
81+
```javascript
82+
Cookies.set('name', { foo: 'bar' });
83+
```
84+
85+
When reading a cookie with the default `Cookies.get()` api, you receive the stringified representation stored in the cookie:
8386

84-
### json
87+
```javascript
88+
Cookies.get('name'); // => '{"foo":"bar"}'
89+
```
8590

86-
Turn on automatic storage of JSON objects passed as the cookie value. Assumes `JSON.stringify` and `JSON.parse`:
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):
8792

8893
```javascript
89-
Cookies.json = true;
94+
Cookies.getJSON('name'); // => { foo: 'bar' }
9095
```
9196

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+
92104
## Cookie Options
93105

94106
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.
@@ -130,11 +142,13 @@ If true, the cookie transmission requires a secure protocol (https). Default: `f
130142
Provide a conversion function as optional last argument for reading, in order to change the cookie's value
131143
to a different representation on the fly.
132144

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

135147
```javascript
136-
Cookies.set('foo', '42');
137-
Cookies.get('foo', Number); // => 42
148+
// 'cookie+with+space' => 'cookie with space'
149+
Cookies.get('foo', function (value) {
150+
return value.replace(/\+/g, ' ');
151+
});
138152
```
139153

140154
Dealing with cookies that have been encoded using `escape` (3rd party cookies):
@@ -143,8 +157,6 @@ Dealing with cookies that have been encoded using `escape` (3rd party cookies):
143157
Cookies.get('foo', unescape);
144158
```
145159

146-
You can pass an arbitrary conversion function.
147-
148160
## Contributing
149161

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

‎src/js.cookie.js‎

Lines changed: 38 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -29,41 +29,52 @@
2929
var unallowedCharsInValue = extend(unallowedChars, {
3030
' ': '%20'
3131
});
32-
function encode(value, charmap) {
32+
33+
function encode (value, charmap) {
3334
for (var character in charmap) {
3435
value = value
3536
.replace(new RegExp(character, 'g'), charmap[character]);
3637
}
3738
return value;
3839
}
3940

40-
function decode(value, charmap) {
41+
function decode (value, charmap) {
4142
for (var character in charmap) {
4243
value = value
4344
.replace(new RegExp(charmap[character], 'g'), character);
4445
}
4546
return value;
4647
}
4748

48-
function parseCookieValue(value) {
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);
58+
}
59+
60+
function processRead (value, converter, json) {
4961
if (value.indexOf('"') === 0) {
5062
// This is a quoted cookie as according to RFC2068, unescape...
5163
value = value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
5264
}
5365

5466
value = decode(value, unallowedCharsInValue);
5567

56-
try {
57-
return api.json ? JSON.parse(value) : value;
58-
} catch(e) {}
59-
}
68+
if (json) {
69+
try {
70+
value = JSON.parse(value);
71+
} catch(e) {}
72+
}
6073

61-
function read(s, converter) {
62-
var value = parseCookieValue(s);
6374
return isFunction(converter) ? converter(value) : value;
6475
}
6576

66-
function extend() {
77+
function extend () {
6778
var key, options;
6879
var i = 0;
6980
var result = {};
@@ -76,15 +87,21 @@
7687
return result;
7788
}
7889

79-
function isFunction(obj) {
90+
function isFunction (obj) {
8091
return Object.prototype.toString.call(obj) === '[object Function]';
8192
}
8293

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

85102
// Write
86103

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

90107
if (typeof options.expires === 'number') {
@@ -93,7 +110,7 @@
93110
}
94111

95112
return (document.cookie = [
96-
encode(key, unallowedCharsInName), '=', encode(api.json ? JSON.stringify(value) : String(value), unallowedCharsInValue),
113+
encode(key, unallowedCharsInName), '=', processWrite(value),
97114
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
98115
options.path ? '; path=' + options.path : '',
99116
options.domain ? '; domain=' + options.domain : '',
@@ -117,21 +134,24 @@
117134
cookie = parts.join('=');
118135

119136
if (key === name) {
120-
// If second argument (value) is a function it's a converter...
121-
result = read(cookie, value);
137+
result = processRead(cookie, converter, this.json);
122138
break;
123139
}
124140

125-
// Prevent storing a cookie that we couldn't decode.
126-
if (!key && (cookie = read(cookie)) !== undefined) {
127-
result[name] = cookie;
141+
if (!key) {
142+
result[name] = processRead(cookie, converter, this.json);
128143
}
129144
}
130145

131146
return result;
132147
};
133148

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

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

0 commit comments

Comments
 (0)