使用Javascript清除所有cookie

时间:2012-05-22 04:51:48

标签: javascript cookies

有没有用javascript清除cookie?

首先,我需要澄清问题。 StackOverflow中的许多帖子都提供this kind of answer。但它正在清除cookie,就像将所有键的值设置为空字符串一样。但我也需要擦除键。我怎么能这样做?

PS:我尝试了document.cookie = null,但它不起作用here

1 个答案:

答案 0 :(得分:0)

我找到的最好方法是使您要删除的Cookie失效,请使用此javascript:

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var 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;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}