1 | <p align="center">
|
2 | <img src="https://cloud.githubusercontent.com/assets/835857/14581711/ba623018-0436-11e6-8fce-d2ccd4d379c9.gif">
|
3 | </p>
|
4 |
|
5 | # JavaScript Cookie [![Build Status](https://travis-ci.org/js-cookie/js-cookie.svg?branch=master)](https://travis-ci.org/js-cookie/js-cookie) [![Code Climate](https://codeclimate.com/github/js-cookie/js-cookie.svg)](https://codeclimate.com/github/js-cookie/js-cookie) [![jsDelivr Hits](https://data.jsdelivr.com/v1/package/npm/js-cookie/badge?style=rounded)](https://www.jsdelivr.com/package/npm/js-cookie)
|
6 |
|
7 | A simple, lightweight JavaScript API for handling cookies
|
8 |
|
9 | * Works in [all](https://saucelabs.com/u/js-cookie) browsers
|
10 | * Accepts [any](#encoding) character
|
11 | * [Heavily](test) tested
|
12 | * No dependency
|
13 | * [Unobtrusive](#json) JSON support
|
14 | * Supports AMD/CommonJS
|
15 | * [RFC 6265](https://tools.ietf.org/html/rfc6265) compliant
|
16 | * Useful [Wiki](https://github.com/js-cookie/js-cookie/wiki)
|
17 | * Enable [custom encoding/decoding](#converters)
|
18 | * **~900 bytes** gzipped!
|
19 |
|
20 | **If you're viewing this at https://github.com/js-cookie/js-cookie, you're reading the documentation for the master branch.
|
21 | [View documentation for the latest release.](https://github.com/js-cookie/js-cookie/tree/latest#readme)**
|
22 |
|
23 | ## Build Status Matrix ([including active Pull Requests](https://github.com/js-cookie/js-cookie/issues/286))
|
24 |
|
25 | [![Selenium Test Status](https://saucelabs.com/browser-matrix/js-cookie.svg)](https://saucelabs.com/u/js-cookie)
|
26 |
|
27 | ## Installation
|
28 |
|
29 | ### Direct download
|
30 |
|
31 | Download the script [here](https://github.com/js-cookie/js-cookie/blob/latest/src/js.cookie.js) and include it (unless you are packaging scripts somehow else):
|
32 |
|
33 | ```html
|
34 | <script src="/path/to/js.cookie.js"></script>
|
35 | ```
|
36 |
|
37 | Or include it via [jsDelivr CDN](https://www.jsdelivr.com/package/npm/js-cookie):
|
38 |
|
39 | ```html
|
40 | <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
|
41 | ```
|
42 |
|
43 | **Do not include the script directly from GitHub (http://raw.github.com/...).** The file is being served as text/plain and as such being blocked
|
44 | in Internet Explorer on Windows 7 for instance (because of the wrong MIME type). Bottom line: GitHub is not a CDN.
|
45 |
|
46 | ### Package Managers
|
47 |
|
48 | JavaScript Cookie supports [npm](https://www.npmjs.com/package/js-cookie) and [Bower](http://bower.io/search/?q=js-cookie) under the name `js-cookie`.
|
49 |
|
50 | #### NPM
|
51 | ```
|
52 | $ npm install js-cookie --save
|
53 | ```
|
54 |
|
55 | ### Module Loaders
|
56 |
|
57 | JavaScript Cookie can also be loaded as an AMD or CommonJS module.
|
58 |
|
59 | ## Basic Usage
|
60 |
|
61 | Create a cookie, valid across the entire site:
|
62 |
|
63 | ```javascript
|
64 | Cookies.set('name', 'value');
|
65 | ```
|
66 |
|
67 | Create a cookie that expires 7 days from now, valid across the entire site:
|
68 |
|
69 | ```javascript
|
70 | Cookies.set('name', 'value', { expires: 7 });
|
71 | ```
|
72 |
|
73 | Create an expiring cookie, valid to the path of the current page:
|
74 |
|
75 | ```javascript
|
76 | Cookies.set('name', 'value', { expires: 7, path: '' });
|
77 | ```
|
78 |
|
79 | Read cookie:
|
80 |
|
81 | ```javascript
|
82 | Cookies.get('name'); // => 'value'
|
83 | Cookies.get('nothing'); // => undefined
|
84 | ```
|
85 |
|
86 | Read all visible cookies:
|
87 |
|
88 | ```javascript
|
89 | Cookies.get(); // => { name: 'value' }
|
90 | ```
|
91 |
|
92 | *Note: It is not possible to read a particular cookie by passing one of the cookie attributes (which may or may not
|
93 | have been used when writing the cookie in question):*
|
94 |
|
95 | ```javascript
|
96 | Cookies.get('foo', { domain: 'sub.example.com' }); // `domain` won't have any effect...!
|
97 | ```
|
98 |
|
99 | The cookie with the name `foo` will only be available on `.get()` if it's visible from where the
|
100 | code is called; the domain and/or path attribute will not have an effect when reading.
|
101 |
|
102 | Delete cookie:
|
103 |
|
104 | ```javascript
|
105 | Cookies.remove('name');
|
106 | ```
|
107 |
|
108 | Delete a cookie valid to the path of the current page:
|
109 |
|
110 | ```javascript
|
111 | Cookies.set('name', 'value', { path: '' });
|
112 | Cookies.remove('name'); // fail!
|
113 | Cookies.remove('name', { path: '' }); // removed!
|
114 | ```
|
115 |
|
116 | *IMPORTANT! When deleting a cookie and you're not relying on the [default attributes](#cookie-attributes), you must pass the exact same path and domain attributes that were used to set the cookie:*
|
117 |
|
118 | ```javascript
|
119 | Cookies.remove('name', { path: '', domain: '.yourdomain.com' });
|
120 | ```
|
121 |
|
122 | *Note: Removing a nonexistent cookie does not raise any exception nor return any value.*
|
123 |
|
124 | ## Namespace conflicts
|
125 |
|
126 | If there is any danger of a conflict with the namespace `Cookies`, the `noConflict` method will allow you to define a new namespace and preserve the original one. This is especially useful when running the script on third party sites e.g. as part of a widget or SDK.
|
127 |
|
128 | ```javascript
|
129 | // Assign the js-cookie api to a different variable and restore the original "window.Cookies"
|
130 | var Cookies2 = Cookies.noConflict();
|
131 | Cookies2.set('name', 'value');
|
132 | ```
|
133 |
|
134 | *Note: The `.noConflict` method is not necessary when using AMD or CommonJS, thus it is not exposed in those environments.*
|
135 |
|
136 | ## JSON
|
137 |
|
138 | js-cookie provides unobtrusive JSON storage for cookies.
|
139 |
|
140 | 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 will store the string representation of the object according to `JSON.stringify`:
|
141 |
|
142 | ```javascript
|
143 | Cookies.set('name', { foo: 'bar' });
|
144 | ```
|
145 |
|
146 | When reading a cookie with the default `Cookies.get` api, you receive the string representation stored in the cookie:
|
147 |
|
148 | ```javascript
|
149 | Cookies.get('name'); // => '{"foo":"bar"}'
|
150 | ```
|
151 |
|
152 | ```javascript
|
153 | Cookies.get(); // => { name: '{"foo":"bar"}' }
|
154 | ```
|
155 |
|
156 | When reading a cookie with the `Cookies.getJSON` api, you receive the parsed representation of the string stored in the cookie according to `JSON.parse`:
|
157 |
|
158 | ```javascript
|
159 | Cookies.getJSON('name'); // => { foo: 'bar' }
|
160 | ```
|
161 |
|
162 | ```javascript
|
163 | Cookies.getJSON(); // => { name: { foo: 'bar' } }
|
164 | ```
|
165 |
|
166 | *Note: To support IE6-7 ([and IE 8 compatibility mode](http://stackoverflow.com/questions/4715373/json-object-undefined-in-internet-explorer-8)) you need to include the JSON-js polyfill: https://github.com/douglascrockford/JSON-js*
|
167 |
|
168 | ## Encoding
|
169 |
|
170 | This project is [RFC 6265](http://tools.ietf.org/html/rfc6265#section-4.1.1) compliant. All special characters that are not allowed in the cookie-name or cookie-value are encoded with each one's UTF-8 Hex equivalent using [percent-encoding](http://en.wikipedia.org/wiki/Percent-encoding).
|
171 | The only character in cookie-name or cookie-value that is allowed and still encoded is the percent `%` character, it is escaped in order to interpret percent input as literal.
|
172 | Please note that the default encoding/decoding strategy is meant to be interoperable [only between cookies that are read/written by js-cookie](https://github.com/js-cookie/js-cookie/pull/200#discussion_r63270778). To override the default encoding/decoding strategy you need to use a [converter](#converters).
|
173 |
|
174 | *Note: According to [RFC 6265](https://tools.ietf.org/html/rfc6265#section-6.1), your cookies may get deleted if they are too big or there are too many cookies in the same domain, [more details here](https://github.com/js-cookie/js-cookie/wiki/Frequently-Asked-Questions#why-are-my-cookies-being-deleted).*
|
175 |
|
176 | ## Cookie Attributes
|
177 |
|
178 | Cookie attributes defaults 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 in the last argument. Per-call attributes override the default attributes.
|
179 |
|
180 | ### expires
|
181 |
|
182 | Define when the cookie will be removed. Value can be a [`Number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) which will be interpreted as days from time of creation or a [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance. If omitted, the cookie becomes a session cookie.
|
183 |
|
184 | To create a cookie that expires in less than a day, you can check the [FAQ on the Wiki](https://github.com/js-cookie/js-cookie/wiki/Frequently-Asked-Questions#expire-cookies-in-less-than-a-day).
|
185 |
|
186 | **Default:** Cookie is removed when the user closes the browser.
|
187 |
|
188 | **Examples:**
|
189 |
|
190 | ```javascript
|
191 | Cookies.set('name', 'value', { expires: 365 });
|
192 | Cookies.get('name'); // => 'value'
|
193 | Cookies.remove('name');
|
194 | ```
|
195 |
|
196 | ### path
|
197 |
|
198 | A [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) indicating the path where the cookie is visible.
|
199 |
|
200 | **Default:** `/`
|
201 |
|
202 | **Examples:**
|
203 |
|
204 | ```javascript
|
205 | Cookies.set('name', 'value', { path: '' });
|
206 | Cookies.get('name'); // => 'value'
|
207 | Cookies.remove('name', { path: '' });
|
208 | ```
|
209 |
|
210 | **Note regarding Internet Explorer:**
|
211 |
|
212 | > Due to an obscure bug in the underlying WinINET InternetGetCookie implementation, IE’s document.cookie will not return a cookie if it was set with a path attribute containing a filename.
|
213 |
|
214 | (From [Internet Explorer Cookie Internals (FAQ)](http://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx))
|
215 |
|
216 | This means one cannot set a path using `window.location.pathname` in case such pathname contains a filename like so: `/check.html` (or at least, such cookie cannot be read correctly).
|
217 |
|
218 | In fact, you should never allow untrusted input to set the cookie attributes or you might be exposed to a [XSS attack](https://github.com/js-cookie/js-cookie/issues/396).
|
219 |
|
220 | ### domain
|
221 |
|
222 | A [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) indicating a valid domain where the cookie should be visible. The cookie will also be visible to all subdomains.
|
223 |
|
224 | **Default:** Cookie is visible only to the domain or subdomain of the page where the cookie was created, except for Internet Explorer (see below).
|
225 |
|
226 | **Examples:**
|
227 |
|
228 | Assuming a cookie that is being created on `site.com`:
|
229 |
|
230 | ```javascript
|
231 | Cookies.set('name', 'value', { domain: 'subdomain.site.com' });
|
232 | Cookies.get('name'); // => undefined (need to read at 'subdomain.site.com')
|
233 | ```
|
234 |
|
235 | **Note regarding Internet Explorer default behavior:**
|
236 |
|
237 | > Q3: If I don’t specify a DOMAIN attribute (for) a cookie, IE sends it to all nested subdomains anyway?
|
238 | > A: Yes, a cookie set on example.com will be sent to sub2.sub1.example.com.
|
239 | > Internet Explorer differs from other browsers in this regard.
|
240 |
|
241 | (From [Internet Explorer Cookie Internals (FAQ)](http://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx))
|
242 |
|
243 | This means that if you omit the `domain` attribute, it will be visible for a subdomain in IE.
|
244 |
|
245 | ### secure
|
246 |
|
247 | Either `true` or `false`, indicating if the cookie transmission requires a secure protocol (https).
|
248 |
|
249 | **Default:** No secure protocol requirement.
|
250 |
|
251 | **Examples:**
|
252 |
|
253 | ```javascript
|
254 | Cookies.set('name', 'value', { secure: true });
|
255 | Cookies.get('name'); // => 'value'
|
256 | Cookies.remove('name');
|
257 | ```
|
258 |
|
259 | ## Converters
|
260 |
|
261 | ### Read
|
262 |
|
263 | Create a new instance of the api that overrides the default decoding implementation.
|
264 | All get methods that rely in a proper decoding to work, such as `Cookies.get()` and `Cookies.get('name')`, will run the converter first for each cookie.
|
265 | The returning String will be used as the cookie value.
|
266 |
|
267 | Example from reading one of the cookies that can only be decoded using the `escape` function:
|
268 |
|
269 | ```javascript
|
270 | document.cookie = 'escaped=%u5317';
|
271 | document.cookie = 'default=%E5%8C%97';
|
272 | var cookies = Cookies.withConverter(function (value, name) {
|
273 | if ( name === 'escaped' ) {
|
274 | return unescape(value);
|
275 | }
|
276 | });
|
277 | cookies.get('escaped'); // 北
|
278 | cookies.get('default'); // 北
|
279 | cookies.get(); // { escaped: '北', default: '北' }
|
280 | ```
|
281 |
|
282 | ### Write
|
283 |
|
284 | Create a new instance of the api that overrides the default encoding implementation:
|
285 |
|
286 | ```javascript
|
287 | Cookies.withConverter({
|
288 | read: function (value, name) {
|
289 | // Read converter
|
290 | },
|
291 | write: function (value, name) {
|
292 | // Write converter
|
293 | }
|
294 | });
|
295 | ```
|
296 |
|
297 | ## Server-side integration
|
298 |
|
299 | Check out the [Servers Docs](SERVER_SIDE.md)
|
300 |
|
301 | ## Contributing
|
302 |
|
303 | Check out the [Contributing Guidelines](CONTRIBUTING.md)
|
304 |
|
305 | ## Security
|
306 |
|
307 | For vulnerability reports, send an e-mail to `jscookieproject at gmail dot com`
|
308 |
|
309 | ## Manual release steps
|
310 |
|
311 | * Increment the "version" attribute of `package.json`
|
312 | * Increment the version number in the `src/js.cookie.js` file
|
313 | * If `major` bump, update jsDelivr CDN major version link on README
|
314 | * Commit with the message "Release version x.x.x"
|
315 | * Create version tag in git
|
316 | * Create a github release and upload the minified file
|
317 | * Change the `latest` tag pointer to the latest commit
|
318 | * `git tag -f latest`
|
319 | * `git push <remote> :refs/tags/latest`
|
320 | * `git push origin master --tags`
|
321 | * Release on npm
|
322 |
|
323 | ## Authors
|
324 |
|
325 | * [Klaus Hartl](https://github.com/carhartl)
|
326 | * [Fagner Brack](https://github.com/FagnerMartinsBrack)
|
327 | * And awesome [contributors](https://github.com/js-cookie/js-cookie/graphs/contributors)
|