Reading and writing cookies for a web app is quite easy with JS Cookie. It is a 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 simplicity 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 https://github.com/js-cookie/js-cookie.
Examples:
Write cookies
Cookies.set('author', 'TL Dev Tech'); Cookies.set('author', 'TL Dev Tech', { expires: 7 }); //expires in 7 days Cookies.set('author', 'TL Dev Tech', { expires: 7, path: '/my-page' }); //affect a page Cookies.set('name', 'value', { domain: 'www.tldevtech.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: 'TL Dev Tech', website: 'www.tldevtech.com' }); //get the cookie's data it normally Cookies.get('author')