// The Lucia project. // Copyright 2023-2026 DSP, inc. All rights reserved. // Authors: // chiayin.kuo@dsp.im (chiayin), 2023/1/31 // imacat.yang@dsp.im (imacat), 2023/9/23 // cindy.chang@dsp.im (Cindy Chang), 2024/5/30 /** @module cookieUtil Browser cookie management utilities. */ /** * Retrieves the value of a cookie by name. * @param {string} name - The cookie name to look up. * @returns {string|null} The cookie value, or null if not found. */ export function getCookie(name) { const nameEqual = name + "="; const cookieArr = document.cookie.split(';'); for (const cookie of cookieArr) { let c = cookie.trim(); if (c.indexOf(nameEqual) === 0) { return c.substring(nameEqual.length, c.length); } } return null; } /** * Sets a cookie with the given name, value, and expiration. * * Cookies are set with the Secure and SameSite=Lax flags. * * @param {string} name - The cookie name. * @param {string} value - The cookie value. * @param {number} [days=1] - Number of days until the cookie expires. */ export function setCookie(name, value, days=1) { let expires = ""; if (days) { const date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toUTCString(); } document.cookie = name + "=" + (value || "") + expires + "; path=/; Secure; SameSite=Lax"; } /** * Sets a session cookie (no expiration) with Secure and SameSite flags. * @param {string} name - The cookie name. * @param {string} value - The cookie value. */ export function setCookieWithoutExpiration(name, value) { document.cookie = name + "=" + (value || "") + "; path=/; Secure; SameSite=Lax"; } /** * Deletes a cookie by setting its Max-Age to a negative value. * @param {string} name - The cookie name to delete. * @param {string} [path='/'] - The path scope of the cookie. */ export function deleteCookie(name, path = '/') { document.cookie = name + '=; Max-Age=-99999999; path=' + path + '; Secure; SameSite=Lax'; }