Skip to content

Commit 1a0d1ed

Browse files
Merge pull request js-cookie#32 from js-cookie/path-defaults
Path default to '/'
2 parents 04b6544 + 4005ea2 commit 1a0d1ed

File tree

4 files changed

+84
-50
lines changed

4 files changed

+84
-50
lines changed

README.md

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -35,22 +35,22 @@ It can also be loaded as an AMD or CommonJS module.
3535

3636
## Basic Usage
3737

38-
Create a session cookie, valid to the path of the current page:
38+
Create a cookie, valid across the entire site:
3939

4040
```javascript
4141
Cookies.set('name', 'value');
4242
```
4343

44-
Create a cookie that expires 7 days from now, valid to the path of the current page:
44+
Create a cookie that expires 7 days from now, valid across the entire site:
4545

4646
```javascript
4747
Cookies.set('name', 'value', { expires: 7 });
4848
```
4949

50-
Create an expiring cookie, valid across the entire site:
50+
Create an expiring cookie, valid to the path of the current page:
5151

5252
```javascript
53-
Cookies.set('name', 'value', { expires: 7, path: '/' });
53+
Cookies.set('name', 'value', { expires: 7, path: '' });
5454
```
5555

5656
Read cookie:
@@ -70,11 +70,14 @@ Delete cookie:
7070

7171
```javascript
7272
Cookies.remove('name');
73+
```
74+
75+
Delete a cookie valid to the path of the current page:
7376

74-
// Need to use the same path, domain and secure attributes that were used when writing the cookie
75-
Cookies.set('name', 'value', { path: '/' });
77+
```javascript
78+
Cookies.set('name', 'value', { path: '' });
7679
Cookies.remove('name'); // fail!
77-
Cookies.remove('name', { path: '/' }); // removed!
80+
Cookies.remove('name', { path: '' }); // removed!
7881
```
7982

8083
*IMPORTANT! when deleting a cookie, you must pass the exact same path, domain and secure attributes that were used to set the cookie, unless you're relying on the [default attributes](#cookie-attributes).*
@@ -137,7 +140,7 @@ Cookie attributes defaults can be set globally by setting properties of the `Coo
137140

138141
Define when the cookie will be removed. Value can be a `Number` which will be interpreted as days from time of creation or a `Date` instance. If omitted, the cookie becomes a session cookie.
139142

140-
**Browser default:** Cookie is removed when the user closes the browser.
143+
**Default:** Cookie is removed when the user closes the browser.
141144

142145
**Examples:**
143146

@@ -151,14 +154,14 @@ Cookies.remove('name');
151154

152155
Define the path where the cookie is available.
153156

154-
**Browser default:** Path of the page where the cookie was created
157+
**Default:** `/`
155158

156159
**Examples:**
157160

158161
```javascript
159-
Cookies.set('name', 'value', { path: '/' });
162+
Cookies.set('name', 'value', { path: '' });
160163
Cookies.get('name'); // => 'value'
161-
Cookies.remove('name', { path: '/' });
164+
Cookies.remove('name', { path: '' });
162165
```
163166

164167
**Note regarding Internet Explorer:**
@@ -173,7 +176,7 @@ This means one cannot set a path using `path: window.location.pathname` in case
173176

174177
Define the domain where the cookie is available
175178

176-
**Browser default:** Domain of the page where the cookie was created
179+
**Default:** Domain of the page where the cookie was created
177180

178181
**Examples:**
179182

@@ -186,7 +189,7 @@ Cookies.get('name'); // => undefined (need to read at 'sub.domain.com')
186189

187190
A `Boolean` indicating if the cookie transmission requires a secure protocol (https)
188191

189-
**Browser default:** No secure protocol requirement
192+
**Default:** No secure protocol requirement
190193

191194
**Examples:**
192195

src/js.cookie.js

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -23,27 +23,29 @@
2323
var i = 0;
2424
var result = {};
2525
for (; i < arguments.length; i++) {
26-
var options = arguments[ i ];
27-
for (var key in options) {
28-
result[key] = options[key];
26+
var attributes = arguments[ i ];
27+
for (var key in attributes) {
28+
result[key] = attributes[key];
2929
}
3030
}
3131
return result;
3232
}
3333

3434
function init (converter) {
35-
function api (key, value, options) {
35+
function api (key, value, attributes) {
3636
var result;
3737

3838
// Write
3939

4040
if (arguments.length > 1) {
41-
options = extend(api.defaults, options);
41+
attributes = extend({
42+
path: '/'
43+
}, api.defaults, attributes);
4244

43-
if (typeof options.expires === 'number') {
45+
if (typeof attributes.expires === 'number') {
4446
var expires = new Date();
45-
expires.setMilliseconds(expires.getMilliseconds() + options.expires * 864e+5);
46-
options.expires = expires;
47+
expires.setMilliseconds(expires.getMilliseconds() + attributes.expires * 864e+5);
48+
attributes.expires = expires;
4749
}
4850

4951
try {
@@ -62,10 +64,10 @@
6264

6365
return (document.cookie = [
6466
key, '=', value,
65-
options.expires && '; expires=' + options.expires.toUTCString(), // use expires attribute, max-age is not supported by IE
66-
options.path && '; path=' + options.path,
67-
options.domain && '; domain=' + options.domain,
68-
options.secure && '; secure'
67+
attributes.expires && '; expires=' + attributes.expires.toUTCString(), // use expires attribute, max-age is not supported by IE
68+
attributes.path && '; path=' + attributes.path,
69+
attributes.domain && '; domain=' + attributes.domain,
70+
attributes.secure && '; secure'
6971
].join(''));
7072
}
7173

@@ -120,8 +122,8 @@
120122
};
121123
api.defaults = {};
122124

123-
api.remove = function (key, options) {
124-
api(key, '', extend(options, {
125+
api.remove = function (key, attributes) {
126+
api(key, '', extend(attributes, {
125127
expires: -1
126128
}));
127129
};

test/tests.js

Lines changed: 45 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -128,15 +128,17 @@ test('expires option as days from now', function () {
128128
expect(1);
129129
var sevenDaysFromNow = new Date();
130130
sevenDaysFromNow.setDate(sevenDaysFromNow.getDate() + 21);
131-
strictEqual(Cookies.set('c', 'v', { expires: 21 }), 'c=v; expires=' + sevenDaysFromNow.toUTCString(),
132-
'should write the cookie string with expires');
131+
var expected = 'c=v; expires=' + sevenDaysFromNow.toUTCString();
132+
var actual = Cookies.set('c', 'v', { expires: 21 }).substring(0, expected.length);
133+
strictEqual(actual, expected, 'should write the cookie string with expires');
133134
});
134135

135136
test('expires option as fraction of a day', function () {
136137
expect(1);
137138

138139
var now = new Date().getTime();
139-
var expires = Date.parse(Cookies.set('c', 'v', { expires: 0.5 }).replace(/.+expires=/, ''));
140+
var stringifiedDate = Cookies.set('c', 'v', { expires: 0.5 }).split('; ')[1].split('=')[1];
141+
var expires = Date.parse(stringifiedDate);
140142

141143
// When we were using Date.setDate() fractions have been ignored
142144
// and expires resulted in the current date. Allow 1000 milliseconds
@@ -148,20 +150,35 @@ test('expires option as Date instance', function () {
148150
expect(1);
149151
var sevenDaysFromNow = new Date();
150152
sevenDaysFromNow.setDate(sevenDaysFromNow.getDate() + 7);
151-
strictEqual(Cookies.set('c', 'v', { expires: sevenDaysFromNow }), 'c=v; expires=' + sevenDaysFromNow.toUTCString(),
152-
'should write the cookie string with expires');
153+
var expected = 'c=v; expires=' + sevenDaysFromNow.toUTCString();
154+
var actual = Cookies.set('c', 'v', { expires: sevenDaysFromNow }).substring(0, expected.length);
155+
strictEqual(actual, expected, 'should write the cookie string with expires');
153156
});
154157

155158
test('return value', function () {
156159
expect(1);
157-
strictEqual(Cookies.set('c', 'v'), 'c=v', 'should return written cookie string');
160+
var expected = 'c=v';
161+
var actual = Cookies.set('c', 'v').substring(0, expected.length);
162+
strictEqual(actual, expected, 'should return written cookie string');
158163
});
159164

160-
test('defaults', function () {
161-
expect(2);
165+
test('default path attribute', function () {
166+
expect(1);
167+
ok(Cookies.set('c', 'v').match(/path=\//), 'should read the default path');
168+
});
169+
170+
test('API for changing defaults', function () {
171+
expect(3);
172+
162173
Cookies.defaults.path = '/foo';
163-
ok(Cookies.set('c', 'v').match(/path=\/foo/), 'should use options from defaults');
164-
ok(Cookies.set('c', 'v', { path: '/bar' }).match(/path=\/bar/), 'options argument has precedence');
174+
ok(Cookies.set('c', 'v').match(/path=\/foo/), 'should use attributes from defaults');
175+
Cookies.remove( 'c', { path: '/foo' });
176+
177+
ok(Cookies.set('c', 'v', { path: '/bar' }).match(/path=\/bar/), 'attributes argument has precedence');
178+
Cookies.remove( 'c', { path: '/bar' });
179+
180+
delete Cookies.defaults.path;
181+
ok(Cookies.set('c', 'v').match(/path=\//), 'should roll back to the default path');
165182
});
166183

167184
module('remove', lifecycle);
@@ -173,20 +190,20 @@ test('deletion', function () {
173190
strictEqual(document.cookie, '', 'should delete the cookie');
174191
});
175192

176-
test('with options', function () {
193+
test('with attributes', function () {
177194
expect(1);
178-
var options = { path: '/' };
179-
Cookies.set('c', 'v', options);
180-
Cookies.remove('c', options);
195+
var attributes = { path: '/' };
196+
Cookies.set('c', 'v', attributes);
197+
Cookies.remove('c', attributes);
181198
strictEqual(document.cookie, '', 'should delete the cookie');
182199
});
183200

184-
test('passing options reference', function () {
201+
test('passing attributes reference', function () {
185202
expect(1);
186-
var options = { path: '/' };
187-
Cookies.set('c', 'v', options);
188-
Cookies.remove('c', options);
189-
deepEqual(options, { path: '/' }, 'won\'t alter options object');
203+
var attributes = { path: '/' };
204+
Cookies.set('c', 'v', attributes);
205+
Cookies.remove('c', attributes);
206+
deepEqual(attributes, { path: '/' }, 'won\'t alter attributes object');
190207
});
191208

192209
module('converters', lifecycle);
@@ -203,7 +220,9 @@ test('should decode a malformed char that matches the decodeURIComponent regex',
203220
document.cookie = 'c=%E3';
204221
var cookies = Cookies.withConverter(unescape);
205222
strictEqual(cookies.get('c'), 'ã', 'should convert the character correctly');
206-
cookies.remove('c');
223+
cookies.remove('c', {
224+
path: ''
225+
});
207226
});
208227

209228
test('should be able to conditionally decode a single malformed cookie', function () {
@@ -213,6 +232,7 @@ test('should be able to conditionally decode a single malformed cookie', functio
213232
return unescape(value);
214233
}
215234
});
235+
216236
document.cookie = 'escaped=%u5317';
217237
strictEqual(cookies.get('escaped'), '北', 'should use a custom method for escaped cookie');
218238

@@ -224,7 +244,11 @@ test('should be able to conditionally decode a single malformed cookie', functio
224244
encoded: '京'
225245
}, 'should retrieve everything');
226246

227-
Object.keys(cookies.get()).forEach(cookies.remove);
247+
Object.keys(cookies.get()).forEach(function (name) {
248+
cookies.remove(name, {
249+
path: ''
250+
});
251+
});
228252
strictEqual(document.cookie, '', 'should remove everything');
229253
});
230254

@@ -303,4 +327,3 @@ test('do not conflict with existent globals', function () {
303327
strictEqual(window.Cookies, 'existent global', 'should restore the original global');
304328
window.Cookies = Cookies;
305329
});
306-

test/utils.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,14 @@
3434

3535
window.lifecycle = {
3636
teardown: function () {
37-
Cookies.defaults = {};
37+
// Remove the cookies created using js-cookie default attributes
3838
Object.keys(Cookies.get()).forEach(Cookies.remove);
39+
// Remove the cookies created using browser default attributes
40+
Object.keys(Cookies.get()).forEach(function (cookie) {
41+
Cookies.remove(cookie, {
42+
path: ''
43+
});
44+
});
3945
}
4046
};
4147
}());

0 commit comments

Comments
 (0)