From 019e76334146dfdf58e16a7762ca94c4a368018a Mon Sep 17 00:00:00 2001 From: Kevin Midboe Date: Thu, 20 May 2021 10:04:26 +0200 Subject: [PATCH] Util functions for set/get cookie. --- frontend/utils.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/frontend/utils.js b/frontend/utils.js index 2c97da7..89bac1c 100644 --- a/frontend/utils.js +++ b/frontend/utils.js @@ -19,4 +19,31 @@ function daysAgo(date) { return Math.round(Math.abs((new Date() - new Date(date)) / day)); } +export function createCookie(name, value, days) { + if (days) { + var date = new Date(); + date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000); + var expires = "; expires=" + date.toGMTString(); + } else var expires = ""; + + const domain = `${window.location.hostname}`; + console.log("cookie:", `${name}=${value + expires}; path=/; domain=${domain}`); + document.cookie = `${name}=${value + expires}; path=/; domain=${domain}`; +} + +export function readCookie(name) { + var nameEQ = name + "="; + var ca = document.cookie.split(";"); + for (var i = 0; i < ca.length; i++) { + var c = ca[i]; + while (c.charAt(0) == " ") c = c.substring(1, c.length); + if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); + } + return null; +} + +export function eraseCookie(name) { + createCookie(name, "", -1); +} + export { dateString, humanReadableDate, daysAgo };