阅读量:0
要通过document.cookie属性管理cookie,可以使用以下方法:
- 获取所有cookie:
var cookies = document.cookie; console.log(cookies);
- 设置cookie:
document.cookie = "cookieName=cookieValue; expires=Thu, 18 Dec 2022 12:00:00 UTC; path=/";
- 获取特定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"));
- 删除cookie:
function deleteCookie(name) { document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'; } deleteCookie("cookieName");
请注意,cookie的设置需要指定过期时间(expires),路径(path)等额外参数,以确保cookie的正确设置和管理。