From 95ea27d3ace9e835c46aea4d687d3dca21393d00 Mon Sep 17 00:00:00 2001 From: igoradamenko Date: Sun, 11 Nov 2018 15:43:22 +0200 Subject: [PATCH] add helper for work with cookies --- web/app/common/cookies.js | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 web/app/common/cookies.js diff --git a/web/app/common/cookies.js b/web/app/common/cookies.js new file mode 100644 index 00000000..6e8ab4f1 --- /dev/null +++ b/web/app/common/cookies.js @@ -0,0 +1,39 @@ +// possible options: expires (in seconds), path, domain, secure +export function setCookie(name, value, options = {}) { + let expires = options.expires; + + if (typeof expires === 'number' && expires) { + const d = new Date(); + d.setTime(d.getTime() + expires * 1000); + expires = options.expires = d; + } + + if (expires && expires.toUTCString) { + options.expires = expires.toUTCString(); + } + + value = encodeURIComponent(value); + + let updatedCookie = `${name}=${value}`; + + for (let propName in options) { + updatedCookie += `; ${propName}`; + if (options[propName] !== true) { + updatedCookie += `=${options[propName]}`; + } + } + + document.cookie = updatedCookie; +} + +export function getCookie(name) { + const matches = document.cookie.match( + new RegExp(`(?:^|; )${name.replace(/([.$?*|{}()[\]\\/+^])/g, '\\$1')}=([^;]*)`) + ); + + return matches ? decodeURIComponent(matches[1]) : undefined; +} + +export function deleteCookie(name) { + setCookie(name, '', { expires: -1 }); +}