Javascript操作cookie,addCookie,getCookie,clearAllCookie,createCookie等操作
Jan 8, 2020 3:50:41 PM
JavaScript对Cookies的操作,JS对Cookie做增删改查。
删除所有cookie
function clearAllCookie() {
document.cookie.split(";").forEach(function (c) {
document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/");
});
};
获取Cookie
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(";");
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == " ") {
c = c.substring(1)
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length)
}
}
return ""
};
添加Cookie
function createCookie(name, value, days, path) {
path = path || "/";
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString()
}
document.cookie = name + "=" + value + expires + "; path=" + path
};
删除Cookie
function deleteCookie(name) {
var expires = new Date();
expires.setTime(expires.getTime()-1);
document.cookie = name + "=;expires=" + expires.toUTCString()
};
版权所属:JavaScript加密
原文地址:https://www.jsjiami.com/article/js-cookies.html
转载时必须以链接形式注明原始出处及本声明。