温馨提示×

如何通过document.cookie管理cookie

小樊
85
2024-06-29 22:47:37
栏目: 编程语言

要通过document.cookie属性管理cookie,可以使用以下方法:

  1. 获取所有cookie:
var cookies = document.cookie;
console.log(cookies);
  1. 设置cookie:
document.cookie = "cookieName=cookieValue; expires=Thu, 18 Dec 2022 12:00:00 UTC; path=/";
  1. 获取特定cookie的值:
function getCookie(name) {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i].trim();
        if (cookie.indexOf(name + "=") === 0) {
            return cookie.substring(name.length + 1, cookie.length);
        }
    }
    return "";
}

console.log(getCookie("cookieName"));
  1. 删除cookie:
function deleteCookie(name) {
    document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
}

deleteCookie("cookieName");

请注意,cookie的设置需要指定过期时间(expires),路径(path)等额外参数,以确保cookie的正确设置和管理。

0