@mt-kit/utils
Version:
88 lines • 3.13 kB
JavaScript
/**
* 封装 Cookie 操作的工具类
*
* 端口、协议不同,不影响 Cookie
*
*
*/
const cookieHelper = {
/**
* 设置 Cookie
* @param {string} name - Cookie 的名称
* @param {string} value - Cookie 的值
* @param {CookieOptions} options - Cookie 的选项
*/
setCookie(name, value, options) {
let cookieString = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
if (options === null || options === void 0 ? void 0 : options.expires) {
const expirationDate = new Date(Date.now() + options.expires * 1000);
cookieString += `; expires=${expirationDate.toUTCString()}`;
}
if (options === null || options === void 0 ? void 0 : options.domain) {
cookieString += `; domain=${options.domain}`;
}
if (options === null || options === void 0 ? void 0 : options.path) {
cookieString += `; path=${options.path}`;
}
if (options === null || options === void 0 ? void 0 : options.secure) {
cookieString += "; secure";
}
if (options === null || options === void 0 ? void 0 : options.sameSite) {
cookieString += `; samesite=${options.sameSite}`;
}
// eslint-disable-next-line unicorn/no-document-cookie
document.cookie = cookieString;
},
/**
* 获取 Cookie 的值
* @param {string} name - Cookie 的名称
* @returns {string|null} Cookie 的值,如果不存在则返回 null
*/
getCookie(name) {
const cookies = document.cookie.split("; ");
for (const cookie of cookies) {
const [cookieName, cookieValue] = cookie.split("=");
if (decodeURIComponent(cookieName) === name) {
return decodeURIComponent(cookieValue);
}
}
return null;
},
/**
* 删除 Cookie
* @param {string} name - Cookie 的名称
* @param {CookieOptions} options - Cookie 的路径(一版不需要)
*/
deleteCookie(name, options) {
if (!this.getCookie(name)) {
return;
}
// 设置过期时间为过去的时间来删除 Cookie
const deleteOptions = {
domain: options === null || options === void 0 ? void 0 : options.domain,
expires: -1,
path: options === null || options === void 0 ? void 0 : options.path,
sameSite: options === null || options === void 0 ? void 0 : options.sameSite,
secure: options === null || options === void 0 ? void 0 : options.secure
};
this.setCookie(name, "", deleteOptions);
}
};
export default cookieHelper;
/*
* // 使用示例
* const cookieOptions: CookieOptions = {
* expires: 3600,
* domain: 'example.com',
* path: '/',
* secure: true,
* sameSite: 'None'
* };
*
* CookieHelper.setCookie('username', 'John Doe', cookieOptions);
* const username = CookieHelper.getCookie('username');
* console.log(username);
*
* CookieHelper.deleteCookie('username', cookieOptions);
*/
//# sourceMappingURL=index.js.map