482

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); } 
2
  • 3
    w3schools has good functions for cookies at w3schools.com/js/js_cookies.asp. You can use setCookie('name', 'value', 0) to delete a cookie. Commented Aug 11, 2017 at 15:56
  • 1
    This answer worked for me above all the others: stackoverflow.com/a/28119715 Commented Oct 7, 2020 at 11:58

16 Answers 16

440

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 + '='); }); } 
Sign up to request clarification or add additional context in comments.

11 Comments

how do i set a function that and check what is my cookies and whether it expire yet?
get_cookie is not defined
The second version of the function no longer works See jsfiddle jsfiddle.net/b27Lgxgf/1. Approach in @Luca 's anwser works
How is this supposed to work? JavaScript doesn't have built-in get_cookie() function.
@MichałPerłakowski I'm pretty sure it was only meant to be a placeholder/reference to an actual function you would define elsewhere.
|
166

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;'; } 

5 Comments

note: in case not working, make sure path is correct. see: developers.google.com/web/tools/chrome-devtools/manage-data/…
domain should be added.
Also worth noting that both path and domain need to have correct values.
Tested, works perfectly even in WKWebView, before page loads. Good job on solution.
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.
60

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.

2 Comments

Set to zero, the cookie will expire when the browser window closes.
@AyexeM refreshing the windows does the job also
35

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.

4 Comments

This was the answer I chose to use, but in my case did not work until I changed it to location.hostname
This worked for me also with the exception of implementing what @Tom said. Changing location.host to location.hostname
Doesn't work for me.
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.
20

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'); 

Comments

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.

3 Comments

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.
I ended up using this: github.com/carhartl/jquery-cookie And you have to delete using path: '/'
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.
17

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"); 

Comments

16

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).

1 Comment

That only works with dev console, unfortunately. Logout.php script doesn't
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);} } } 

Comments

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' } 

Comments

0
if ("JSESSIONID".equals(cookie.getName()) || "LtpaToken2".equals(cookie.getName())) { cookie.setValue(""); cookie.setPath("/"); cookie.setMaxAge(0); cookie.setHttpOnly(true); response.addCookie(cookie); } 

Comments

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

Comments

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=/"; 

Comments

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.

Comments

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

Comments

0

Check my below way as i set it empty to create old one and set the new one, works fine 100%:-

function setCookie(name,value,days) { let expires = ""; if (days) { let date = new Date(); date.setTime(date.getTime() + (days*24*60*60*1000)); expires = "; expires=" + date.toUTCString(); } document.cookie = name + "=" + (value || "") + expires + "; path=/"; } setCookie('source','',''); setCookie('source',facebook,'1'); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.