Javascript操作cookie,addCookie,getCookie,clearAllCookie等操作

2年前 (2022) 程序员胖胖胖虎阿
270 0 0

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()
};

相关文章

暂无评论

暂无评论...