Reading and writing cookie for a web app is quite easy with JS Coookie. It is lightweight JavaScript plugin for reading and writing browser cookies.
This plugin used to be a jQuery one. However, the author decided to convert it to a JavaScript library for simple and ease of use.
JS Coookie features:
- It supports all web browsers.
- Unicode characters can be stored.
- It works without any dependencies.
- It supports unobtrusive JSON, AMD/CommonJS, and is RFC 6265 compliant.
- It also allows custom encoding/decoding.
The library’s homepage is at https://github.com/js-cookie/js-cookie.
Examples:
Write cookies
Cookies.set('author', 'TL Templates'); Cookies.set('author', 'TL Templates', { expires: 7 }); //expires in 7 days Cookies.set('author', 'TL Templates', { expires: 7, path: '/my-page' }); //affect a page Cookies.set('name', 'value', { domain: 'tltemplates.com' }); //affect domain Cookies.set('name', 'value', { secure: true }); //cookie's transmission requires a https
Read cookies
Cookies.get('author'); //get cookie based on name Cookies.get(); //get all cookie
Delete cookies
Cookies.remove('author'); Cookies.remove('author', { path: '' }); //remove the cookie on certain path only
Pass an array or object
The library offers support for JSON storage.
Cookies.set('author', { name: 'TLTemplates', website: 'tltemplates.com' }); //get the cookie's data it normally Cookies.get('author')