简体   繁体   中英

How to delete a cookie in javascript

I am trying to delete a cookie with this function , but it doesnt work..

deleteAllCookies();

function deleteAllCookies() {
    var cookies = document.cookie.split(";");

    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var eqPos = cookie.indexOf("=");
        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }
}

Why the cookie is in my browser, even after i activate that function ...

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 eraseCookie(name) {
    createCookie(name,"",-1);
}

Source: http://www.quirksmode.org/js/cookies.html

The standard way of deleting a cookie in JavaScript is to overwrite cookie's value to empty value and expires date to a passed date. Something like this.

Example , this should delete acctoken cookie.

document.cookie = "acctoken=; expires=Thu, 01 Jan 1970 00:00:00 UTC;"

If your cookie is in different domain or sub-doman , then you will have to explicitly specify domain/sub-domain in overwritten cookie.

document.cookie = "acctoken=; expires=Thu, 01 Jan 1970 00:00:00 UTC; domain=example.com"

More, context in this answer .

var cookies = document.cookie.split(";");

for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i];
    var eqPos = cookie.indexOf("=");
    var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
    document.cookie = cname + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT ; path = /;";

Answers above are correct but don't forget to add path

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM