|
/** |
|
* Cookie functions |
|
* @see https://javascript.info/cookie |
|
*/ |
|
|
|
/** |
|
* Returns the cookie with the given name, |
|
* or undefined if not found |
|
* @see https://javascript.info/cookie#getcookie-name |
|
* @param {string} name Cookie name |
|
* @returns {string} Cookie value |
|
*/ |
|
export function getCookie(name) { |
|
let matches = document.cookie.match(new RegExp( |
|
'(?:^|; )' + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + '=([^;]*)' |
|
)); |
|
return matches ? decodeURIComponent(matches[1]) : undefined; |
|
} |
|
|
|
/** |
|
* Sets the cookie name to the given value with path=/ by default |
|
* @see https://javascript.info/cookie#setcookie-name-value-options |
|
* @param {string} name Cookie name |
|
* @param {string} value Cookie value |
|
* @param {Object} options Additional params |
|
*/ |
|
export function setCookie(name, value, options = {}) { |
|
options = { |
|
path: '/', |
|
...options |
|
}; |
|
|
|
if (options.hasOwnProperty('expires') && options.expires.hasOwnProperty('toUTCString')) { |
|
options.expires = options.expires.toUTCString(); |
|
} |
|
|
|
let updatedCookie = encodeURIComponent(name) + '=' + encodeURIComponent(value); |
|
|
|
for (let optionKey in options) { |
|
updatedCookie += '; ' + optionKey; |
|
let optionValue = options[optionKey]; |
|
if (optionValue !== true) { |
|
updatedCookie += '=' + optionValue; |
|
} |
|
} |
|
|
|
document.cookie = updatedCookie; |
|
} |
|
|
|
/** |
|
* Deletes the cookie with a given name |
|
* @param {string} name Cookie name |
|
*/ |
|
export function deleteCookie(name) { |
|
setCookie(name, "", { |
|
'max-age': -1 |
|
}); |
|
} |