@cimo/jsmvcfw
Version:
Javascript mvc framework. Light, fast and secure.
43 lines • 1.47 kB
JavaScript
import { getAppLabel } from "./JsMvcFw.js";
const isJson = (value) => {
try {
JSON.parse(value);
return true;
}
catch {
return false;
}
};
const isBase64 = (value) => {
return /^[A-Za-z0-9+/]*={0,2}$/.test(value) && value.length % 4 === 0;
};
const escapeRegExp = (value) => {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
};
export const writeCookie = (tag, value, expire = "", httpOnly = "", path = "/") => {
const encodedData = window.btoa(encodeURIComponent(JSON.stringify(value)));
document.cookie = `${getAppLabel()}_${tag}=${encodedData};expires=${expire};${httpOnly};path=${path};Secure`;
};
export const readCookie = (tag) => {
let result;
const name = escapeRegExp(`${getAppLabel()}_${tag}`);
const resultMatch = document.cookie.match(new RegExp(`${name}=([^;]+)`));
if (resultMatch) {
let cookie = resultMatch[1];
if (isBase64(cookie.replaceAll('"', ""))) {
cookie = window.atob(cookie.replaceAll('"', ""));
}
const decodeUriCookie = decodeURIComponent(cookie);
if (isJson(decodeUriCookie)) {
result = JSON.parse(decodeUriCookie);
}
else {
result = decodeUriCookie;
}
}
return result;
};
export const deleteCookie = (tag) => {
document.cookie = `${getAppLabel()}_${tag}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
};
//# sourceMappingURL=JsMvcFwCookie.js.map