You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

327 lines
12 KiB

4 years ago
  1. <p align="center">
  2. <img src="https://cloud.githubusercontent.com/assets/835857/14581711/ba623018-0436-11e6-8fce-d2ccd4d379c9.gif">
  3. </p>
  4. # 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)
  5. A simple, lightweight JavaScript API for handling cookies
  6. * Works in [all](https://saucelabs.com/u/js-cookie) browsers
  7. * Accepts [any](#encoding) character
  8. * [Heavily](test) tested
  9. * No dependency
  10. * [Unobtrusive](#json) JSON support
  11. * Supports AMD/CommonJS
  12. * [RFC 6265](https://tools.ietf.org/html/rfc6265) compliant
  13. * Useful [Wiki](https://github.com/js-cookie/js-cookie/wiki)
  14. * Enable [custom encoding/decoding](#converters)
  15. * **~900 bytes** gzipped!
  16. **If you're viewing this at https://github.com/js-cookie/js-cookie, you're reading the documentation for the master branch.
  17. [View documentation for the latest release.](https://github.com/js-cookie/js-cookie/tree/latest#readme)**
  18. ## Build Status Matrix ([including active Pull Requests](https://github.com/js-cookie/js-cookie/issues/286))
  19. [![Selenium Test Status](https://saucelabs.com/browser-matrix/js-cookie.svg)](https://saucelabs.com/u/js-cookie)
  20. ## Installation
  21. ### Direct download
  22. 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):
  23. ```html
  24. <script src="/path/to/js.cookie.js"></script>
  25. ```
  26. Or include it via [jsDelivr CDN](https://www.jsdelivr.com/package/npm/js-cookie):
  27. ```html
  28. <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
  29. ```
  30. **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
  31. in Internet Explorer on Windows 7 for instance (because of the wrong MIME type). Bottom line: GitHub is not a CDN.
  32. ### Package Managers
  33. 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`.
  34. #### NPM
  35. ```
  36. $ npm install js-cookie --save
  37. ```
  38. ### Module Loaders
  39. JavaScript Cookie can also be loaded as an AMD or CommonJS module.
  40. ## Basic Usage
  41. Create a cookie, valid across the entire site:
  42. ```javascript
  43. Cookies.set('name', 'value');
  44. ```
  45. Create a cookie that expires 7 days from now, valid across the entire site:
  46. ```javascript
  47. Cookies.set('name', 'value', { expires: 7 });
  48. ```
  49. Create an expiring cookie, valid to the path of the current page:
  50. ```javascript
  51. Cookies.set('name', 'value', { expires: 7, path: '' });
  52. ```
  53. Read cookie:
  54. ```javascript
  55. Cookies.get('name'); // => 'value'
  56. Cookies.get('nothing'); // => undefined
  57. ```
  58. Read all visible cookies:
  59. ```javascript
  60. Cookies.get(); // => { name: 'value' }
  61. ```
  62. *Note: It is not possible to read a particular cookie by passing one of the cookie attributes (which may or may not
  63. have been used when writing the cookie in question):*
  64. ```javascript
  65. Cookies.get('foo', { domain: 'sub.example.com' }); // `domain` won't have any effect...!
  66. ```
  67. The cookie with the name `foo` will only be available on `.get()` if it's visible from where the
  68. code is called; the domain and/or path attribute will not have an effect when reading.
  69. Delete cookie:
  70. ```javascript
  71. Cookies.remove('name');
  72. ```
  73. Delete a cookie valid to the path of the current page:
  74. ```javascript
  75. Cookies.set('name', 'value', { path: '' });
  76. Cookies.remove('name'); // fail!
  77. Cookies.remove('name', { path: '' }); // removed!
  78. ```
  79. *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:*
  80. ```javascript
  81. Cookies.remove('name', { path: '', domain: '.yourdomain.com' });
  82. ```
  83. *Note: Removing a nonexistent cookie does not raise any exception nor return any value.*
  84. ## Namespace conflicts
  85. 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.
  86. ```javascript
  87. // Assign the js-cookie api to a different variable and restore the original "window.Cookies"
  88. var Cookies2 = Cookies.noConflict();
  89. Cookies2.set('name', 'value');
  90. ```
  91. *Note: The `.noConflict` method is not necessary when using AMD or CommonJS, thus it is not exposed in those environments.*
  92. ## JSON
  93. js-cookie provides unobtrusive JSON storage for cookies.
  94. 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`:
  95. ```javascript
  96. Cookies.set('name', { foo: 'bar' });
  97. ```
  98. When reading a cookie with the default `Cookies.get` api, you receive the string representation stored in the cookie:
  99. ```javascript
  100. Cookies.get('name'); // => '{"foo":"bar"}'
  101. ```
  102. ```javascript
  103. Cookies.get(); // => { name: '{"foo":"bar"}' }
  104. ```
  105. 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`:
  106. ```javascript
  107. Cookies.getJSON('name'); // => { foo: 'bar' }
  108. ```
  109. ```javascript
  110. Cookies.getJSON(); // => { name: { foo: 'bar' } }
  111. ```
  112. *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*
  113. ## Encoding
  114. 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).
  115. 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.
  116. 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).
  117. *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).*
  118. ## Cookie Attributes
  119. 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.
  120. ### expires
  121. 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.
  122. 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).
  123. **Default:** Cookie is removed when the user closes the browser.
  124. **Examples:**
  125. ```javascript
  126. Cookies.set('name', 'value', { expires: 365 });
  127. Cookies.get('name'); // => 'value'
  128. Cookies.remove('name');
  129. ```
  130. ### path
  131. A [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) indicating the path where the cookie is visible.
  132. **Default:** `/`
  133. **Examples:**
  134. ```javascript
  135. Cookies.set('name', 'value', { path: '' });
  136. Cookies.get('name'); // => 'value'
  137. Cookies.remove('name', { path: '' });
  138. ```
  139. **Note regarding Internet Explorer:**
  140. > 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.
  141. (From [Internet Explorer Cookie Internals (FAQ)](http://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx))
  142. 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).
  143. 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).
  144. ### domain
  145. 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.
  146. **Default:** Cookie is visible only to the domain or subdomain of the page where the cookie was created, except for Internet Explorer (see below).
  147. **Examples:**
  148. Assuming a cookie that is being created on `site.com`:
  149. ```javascript
  150. Cookies.set('name', 'value', { domain: 'subdomain.site.com' });
  151. Cookies.get('name'); // => undefined (need to read at 'subdomain.site.com')
  152. ```
  153. **Note regarding Internet Explorer default behavior:**
  154. > Q3: If I don’t specify a DOMAIN attribute (for) a cookie, IE sends it to all nested subdomains anyway?
  155. > A: Yes, a cookie set on example.com will be sent to sub2.sub1.example.com.
  156. > Internet Explorer differs from other browsers in this regard.
  157. (From [Internet Explorer Cookie Internals (FAQ)](http://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx))
  158. This means that if you omit the `domain` attribute, it will be visible for a subdomain in IE.
  159. ### secure
  160. Either `true` or `false`, indicating if the cookie transmission requires a secure protocol (https).
  161. **Default:** No secure protocol requirement.
  162. **Examples:**
  163. ```javascript
  164. Cookies.set('name', 'value', { secure: true });
  165. Cookies.get('name'); // => 'value'
  166. Cookies.remove('name');
  167. ```
  168. ## Converters
  169. ### Read
  170. Create a new instance of the api that overrides the default decoding implementation.
  171. 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.
  172. The returning String will be used as the cookie value.
  173. Example from reading one of the cookies that can only be decoded using the `escape` function:
  174. ```javascript
  175. document.cookie = 'escaped=%u5317';
  176. document.cookie = 'default=%E5%8C%97';
  177. var cookies = Cookies.withConverter(function (value, name) {
  178. if ( name === 'escaped' ) {
  179. return unescape(value);
  180. }
  181. });
  182. cookies.get('escaped'); // 北
  183. cookies.get('default'); // 北
  184. cookies.get(); // { escaped: '北', default: '北' }
  185. ```
  186. ### Write
  187. Create a new instance of the api that overrides the default encoding implementation:
  188. ```javascript
  189. Cookies.withConverter({
  190. read: function (value, name) {
  191. // Read converter
  192. },
  193. write: function (value, name) {
  194. // Write converter
  195. }
  196. });
  197. ```
  198. ## Server-side integration
  199. Check out the [Servers Docs](SERVER_SIDE.md)
  200. ## Contributing
  201. Check out the [Contributing Guidelines](CONTRIBUTING.md)
  202. ## Security
  203. For vulnerability reports, send an e-mail to `jscookieproject at gmail dot com`
  204. ## Manual release steps
  205. * Increment the "version" attribute of `package.json`
  206. * Increment the version number in the `src/js.cookie.js` file
  207. * If `major` bump, update jsDelivr CDN major version link on README
  208. * Commit with the message "Release version x.x.x"
  209. * Create version tag in git
  210. * Create a github release and upload the minified file
  211. * Change the `latest` tag pointer to the latest commit
  212. * `git tag -f latest`
  213. * `git push <remote> :refs/tags/latest`
  214. * `git push origin master --tags`
  215. * Release on npm
  216. ## Authors
  217. * [Klaus Hartl](https://github.com/carhartl)
  218. * [Fagner Brack](https://github.com/FagnerMartinsBrack)
  219. * And awesome [contributors](https://github.com/js-cookie/js-cookie/graphs/contributors)