kawkab-frontend
Version:
Kawkab frontend is a frontend library for the Kawkab framework
51 lines (50 loc) • 1.46 kB
JavaScript
/**
* Reads a specific cookie value from the browser.
* @param name The name of the cookie.
* @returns The cookie value as a string, or null if not found.
*/
function get(name, defaultValue) {
if (typeof document === 'undefined') {
return null;
}
const match = document.cookie.match(new RegExp('(^|; ?)' + name + '=([^;]+)'));
return match ? match[2] : defaultValue || null;
}
/**
* Sets a cookie value in the browser.
* @param name The name of the cookie.
* @param value The value to be stored.
* @param days The number of days the cookie will be valid for.
*/
function set(name, value, days = 365) {
if (typeof document !== 'undefined') {
const expires = new Date(Date.now() + days * 864e5).toUTCString();
document.cookie = `${name}=${value}; expires=${expires}; path=/`;
}
}
/**
* Checks if a cookie with the given name exists.
* @param name The name of the cookie to check.
* @returns True if the cookie exists, false otherwise.
*/
function has(name) {
if (typeof document === 'undefined') {
return false;
}
// A cookie exists if its value is not null.
return get(name) !== null;
}
/**
* Removes a specific cookie from the browser.
* @param name The name of the cookie to remove.
*/
function remove(name) {
// To remove a cookie, we set its expiration date to the past.
set(name, '', -1);
}
export const Cookie = {
get,
set,
has,
remove,
};