Cookie 本身并不直接保存 JavaScript 对象,而是保存字符串。然而,可以通过序列化和反序列化的过程,在 Cookie 中存储和读取 JavaScript 对象。
Cookie 是一种存储在用户浏览器上的小型文本文件,用于保存用户相关的信息,如登录状态、偏好设置等。每次浏览器向服务器发送请求时,都会携带这些 Cookie 信息。
由于 Cookie 只能保存字符串,因此需要将 JavaScript 对象转换为字符串格式(通常使用 JSON.stringify
方法),然后在读取时再将字符串转换回对象(使用 JSON.parse
方法)。
function setCookie(name, value, days) {
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=/";
}
const user = { name: "John", age: 30 };
setCookie("user", JSON.stringify(user), 7); // 保存对象到 Cookie,有效期为7天
function getCookie(name) {
const nameEQ = name + "=";
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
const userCookie = getCookie("user");
const userObject = JSON.parse(userCookie); // 从 Cookie 中读取并转换回对象
console.log(userObject); // 输出: { name: "John", age: 30 }
问题:Cookie 大小限制和安全性问题。
HttpOnly
标志来防止 JavaScript 访问某些敏感 Cookie,从而降低 XSS 攻击的风险。localStorage
或服务器端存储。通过上述方法,可以在应用中有效地利用 Cookie 来保存和管理 JavaScript 对象。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云