UNPKG

1.47 kBJavaScriptView Raw
1import {root} from './root';
2
3/**
4 * Cookie utilities
5 */
6
7const doc = root.document;
8
9export default {
10
11 /**
12 * Write a cookie
13 * @param {String} name Name of the cookie
14 * @param {String} value Value of the cookie
15 * @param {Number} hours Cookie duration in hours
16 */
17 write(name, value, hours) {
18 let expire = '';
19 if (hours) {
20 expire = new Date((new Date()).getTime() + hours * 3600000);
21 expire = '; expires=' + expire.toGMTString();
22 }
23 doc.cookie = name + '=' + escape(value) + expire;
24 },
25
26 /**
27 * Read a cookie
28 * @param {String} name Name of the cookie
29 * @returns {String} Value of the cookie
30 */
31 read(name) {
32 let cookieValue = '',
33 search = name + '=';
34 if (doc.cookie.length > 0) {
35 let cookie = doc.cookie,
36 offset = cookie.indexOf(search);
37 if (offset !== -1) {
38 offset += search.length;
39 let end = cookie.indexOf(';', offset);
40 if (end === -1) {
41 end = cookie.length;
42 }
43 cookieValue = unescape(cookie.substring(offset, end));
44 }
45 }
46 return cookieValue;
47 },
48
49 /**
50 * Remove a cookie
51 * @param {String} name Name of the cookie
52 */
53 remove(name) {
54 this.write(name, '', -1);
55 }
56
57};