How to delete a cookie?
Asked Answered
P

15

470

Is my function of creating a cookie correct? How do I delete the cookie at the beginning of my program? is there a simple coding?

function createCookie(name,value,days)
function setCookie(c_name,value,1) {
  document.cookie = c_name + "=" +escape(value);
}

setCookie('cookie_name',mac);

function eraseCookie(c_name) {
  createCookie(cookie_name,"",-1);
}
Parson answered 27/1, 2010 at 3:27 Comment(2)
w3schools has good functions for cookies at w3schools.com/js/js_cookies.asp. You can use setCookie('name', 'value', 0) to delete a cookie.Contrarious
This answer worked for me above all the others: stackoverflow.com/a/28119715Benner
F
429

Try this:

function delete_cookie( name, path, domain ) {
  if( get_cookie( name ) ) {
    document.cookie = name + "=" +
      ((path) ? ";path="+path:"")+
      ((domain)?";domain="+domain:"") +
      ";expires=Thu, 01 Jan 1970 00:00:01 GMT";
  }
}

You can define get_cookie() like this:

function get_cookie(name){
    return document.cookie.split(';').some(c => {
        return c.trim().startsWith(name + '=');
    });
}
Frisse answered 27/1, 2010 at 3:34 Comment(11)
how do i set a function that and check what is my cookies and whether it expire yet?Parson
@Kennedy jason's answer might be usefulFrisse
i thought of having a function to view my cookie first.. do you have any coding for that? i want to see it when everytime i visit the webpage, it automatically pop-up an alert for it.Parson
get_cookie is not definedRightly
The second version of the function no longer works See jsfiddle jsfiddle.net/b27Lgxgf/1. Approach in @Luca 's anwser worksMorril
How is this supposed to work? JavaScript doesn't have built-in get_cookie() function.Tenorite
@MichałPerłakowski I'm pretty sure it was only meant to be a placeholder/reference to an actual function you would define elsewhere.Radbourne
It is important to remember when testing the cookie has been deleted that you need to refresh the cookies list to see if the cookie has gone, I had to do this in Chrome debugger.Abydos
I've got a more specific question regarding this, I'll be thankful if you take a look: https://mcmap.net/q/81256/-deleting-cookie-how-to-get-its-path-and-domain/3995261Undying
Is there an advantage to use expires=... instead of Max-Age=0? And using the Epoch date with 00:00:01 instead of 00:00:00?Skid
get_cookie is awkwardly named. Should be has_cookie.Indignant
A
164

Here a good link on Quirksmode.

function setCookie(name,value,days) {
    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=/";
}
function getCookie(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) {   
    document.cookie = name+'=; Max-Age=-99999999;';  
}
Andes answered 26/1, 2010 at 9:29 Comment(5)
note: in case not working, make sure path is correct. see: developers.google.com/web/tools/chrome-devtools/manage-data/…Pena
domain should be added.Clovah
Also worth noting that both path and domain need to have correct values.Trovillion
Tested, works perfectly even in WKWebView, before page loads. Good job on solution.Staid
This one didn't work for me in Firefox (I didn't test it elsewhere). Possible because of the location.host missing. The Luca Borrione answer did; setCookie(name, "", null , null , null, 1); Although the other two functions work well.Isley
M
58

would this work?

function eraseCookie(name) {
    document.cookie = name + '=; Max-Age=0'
}

I know Max-Age causes the cookie to be a session cookie in IE when creating the cookie. Not sure how it works when deleting cookies.

Marjorymarjy answered 12/2, 2013 at 16:57 Comment(2)
Set to zero, the cookie will expire when the browser window closes.Comatose
@AyexeM refreshing the windows does the job alsoGosnell
I
36

Some of the other solutions might not work if you created the cookie manually.

Here's a quick way to delete a cookie:

document.cookie = 'COOKIE_NAME=; Max-Age=0; path=/; domain=' + location.host;

If this doesn't work, try replacing location.host with location.hostname in the snippet above.

Ibby answered 25/8, 2019 at 7:21 Comment(4)
This was the answer I chose to use, but in my case did not work until I changed it to location.hostnameConsistency
This worked for me also with the exception of implementing what @Consistency said. Changing location.host to location.hostnameAppeasement
Doesn't work for me.Ayrshire
This is the best answer because you don't need complex parsing and selection from all the cookies in document.cookie. The browser will automatically delete the cookie at COOKIE_NAME and leave the rest alone. You can also set a negative value.Colemancolemanite
C
19

Here is an implementation of a delete cookie function with unicode support from Mozilla:

function removeItem(sKey, sPath, sDomain) {
    document.cookie = encodeURIComponent(sKey) + 
                  "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + 
                  (sDomain ? "; domain=" + sDomain : "") + 
                  (sPath ? "; path=" + sPath : "");
}

removeItem("cookieName");

If you use AngularJs, try $cookies.remove (underneath it uses a similar approach):

$cookies.remove('cookieName');
Conspiracy answered 22/5, 2015 at 1:41 Comment(0)
T
18

You can do this by setting the date of expiry to yesterday.

Setting it to "-1" doesn't work. That marks a cookie as a Sessioncookie.

Theona answered 22/1, 2012 at 13:51 Comment(3)
your example does not work if you set cookie on another page and try to delete it from a different page. the set works, but cannot delete it.Cannery
I ended up using this: github.com/carhartl/jquery-cookie And you have to delete using path: '/'Cannery
This is a good approach except... just set expiry time to zero. That will cause instant expiration, and not be confusing to anyone ("Why did the developer set expiry time to yesterday? Was that a mistake, did they want a one-day life span?"). Write code so that it makes more sense, and your life will be less confusing down the line. This is an undervalued philosophy in coding nowadays... Even MDN suggests setting expiry time to zero to delete a cookie.Meticulous
S
16

To delete a cookie I set it again with an empty value and expiring in 1 second. In details, I always use one of the following flavours (I tend to prefer the second one):

1.

    function setCookie(key, value, expireDays, expireHours, expireMinutes, expireSeconds) {
        var expireDate = new Date();
        if (expireDays) {
            expireDate.setDate(expireDate.getDate() + expireDays);
        }
        if (expireHours) {
            expireDate.setHours(expireDate.getHours() + expireHours);
        }
        if (expireMinutes) {
            expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
        }
        if (expireSeconds) {
            expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
        }
        document.cookie = key +"="+ escape(value) +
            ";domain="+ window.location.hostname +
            ";path=/"+
            ";expires="+expireDate.toUTCString();
    }

    function deleteCookie(name) {
        setCookie(name, "", null , null , null, 1);
    }

Usage:

setCookie("reminder", "buyCoffee", null, null, 20);
deleteCookie("reminder");

2

    function setCookie(params) {
        var name            = params.name,
            value           = params.value,
            expireDays      = params.days,
            expireHours     = params.hours,
            expireMinutes   = params.minutes,
            expireSeconds   = params.seconds;

        var expireDate = new Date();
        if (expireDays) {
            expireDate.setDate(expireDate.getDate() + expireDays);
        }
        if (expireHours) {
            expireDate.setHours(expireDate.getHours() + expireHours);
        }
        if (expireMinutes) {
            expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
        }
        if (expireSeconds) {
            expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
        }

        document.cookie = name +"="+ escape(value) +
            ";domain="+ window.location.hostname +
            ";path=/"+
            ";expires="+expireDate.toUTCString();
    }

    function deleteCookie(name) {
        setCookie({name: name, value: "", seconds: 1});
    }

Usage:

setCookie({name: "reminder", value: "buyCoffee", minutes: 20});
deleteCookie("reminder");
Sack answered 18/2, 2017 at 18:42 Comment(0)
S
14

For people who just want 1 line of code to delete a cookie:

If you created a cookie, for example in a web browser console with document.cookie = "test=hello"

You can delete it with:

document.cookie = "test=;expires=" + new Date(0).toUTCString()

Or if you prefer to write the UTC date directly:

document.cookie = "test=;expires=Thu, 01 Jan 1970 00:00:00 GMT"

If you are on a different path than the cookie (for example if you want to delete a cookie that is used on all paths), you can add path=/; after test=; and if you are on a different domain (for example when a cookie is set for all subdomains by using .example.com instead of www.example.com), you can add domain=.example.com; after test=;.

Update: instead of expires=..., using Max-Age=0 like in other answers works also (tested with Firefox).

Skid answered 19/7, 2021 at 15:24 Comment(1)
That only works with dev console, unfortunately. Logout.php script doesn'tHangup
C
8

I had trouble deleting a cookie made via JavaScript and after I added the host it worked (scroll the code below to the right to see the location.host). After clearing the cookies on a domain try the following to see the results:

if (document.cookie.length==0)
{
 document.cookie = 'name=example; expires='+new Date((new Date()).valueOf()+1000*60*60*24*15)+'; path=/; domain='+location.host;

 if (document.cookie.length==0) {alert('Cookies disabled');}
 else
 {
  document.cookie = 'name=example; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain='+location.host;

  if (document.cookie.length==0) {alert('Created AND deleted cookie successfully.');}
  else {alert('document.cookies.length = '+document.cookies.length);}
 }
}
Castoff answered 16/1, 2018 at 3:41 Comment(0)
R
5

I use this on my websites that works on Chrome and Firefox.

function delete_cookie(name) { document.cookie = name +'=; Path=/;  Domain=' + location.host +  '; Expires=Thu, 01 Jan 1970 00:00:01 GMT; SameSite=None; Secure' }
Reservist answered 23/9, 2021 at 0:33 Comment(0)
U
0
if ("JSESSIONID".equals(cookie.getName()) || "LtpaToken2".equals(cookie.getName())) {
                cookie.setValue("");
                cookie.setPath("/");
                cookie.setMaxAge(0);
                cookie.setHttpOnly(true);
                response.addCookie(cookie);
}
Unbalance answered 1/7, 2022 at 20:16 Comment(0)
E
0

I used to generate the cookie from backend and redirect to frontend. The only way I got it working has been to set the expires date in the past in the backned and redirect back on frontend

Elconin answered 31/12, 2022 at 13:54 Comment(0)
G
0

We don't have the ability to delete cookies in JavaScript, so to delete it we need to create another cookie with an earlier date.

Set Cookie

let expires = null
const cookieName = 'userlogin'
const d = new Date();
d.setTime(d.getTime() + 2 * 24 * 60 * 60 * 1000);
document.cookie = cookieName + "=" + value+ ";" + expires + ";path=/";

Delete Cookie

let expires = null
const d = new Date();
d.setTime(d.getTime() - 2 * 24 * 60 * 60 * 1000);
expires = "expires=" + d.toUTCString();
document.cookie = 'userlogin' + "=" + value+ ";" + expires + ";path=/";
Grajeda answered 31/1, 2023 at 19:58 Comment(0)
S
0

If you want to erase every single cookie at once, define the eraseCookies function like this:

function eraseCookies() {
    cookies = document.cookie.split("; ").map((a) => a.split("=")[0]) // Get the cookie names
    for (var i in cookies) {
        document.cookie = cookies[i] + "=;expires=" + new Date(0).toUTCString() // Erase each cookie
    }
}

Then you can erase all cookies by calling eraseCookies with no arguments.

Credits to this answer for how to erase a single cookie.

Sunglass answered 4/9, 2023 at 13:45 Comment(0)
A
0

delete by:

document.cookie = name+'=; Max-Age=0; path=/; domain=' + location.hostname+";expires=Thu, 01 Jan 1970 00:00:01 GMT";

Use location.hostname instead of location.host because location.host also returns a port when it's specified

name is the cookie name

Audible answered 8/3 at 14:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.