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);
}
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 + '=');
});
}
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;';
}
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.
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.
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');
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.
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");
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).
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);}
}
}
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' }
if ("JSESSIONID".equals(cookie.getName()) || "LtpaToken2".equals(cookie.getName())) {
cookie.setValue("");
cookie.setPath("/");
cookie.setMaxAge(0);
cookie.setHttpOnly(true);
response.addCookie(cookie);
}
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
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=/";
I have a simple little script which I am using to set a cookie:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
The problem I have this cookie is only set on one page, not across the whole domain.
How can I adjust this function so that the cookie remains across the whole domain?
You can specifiy domain ;domain=.example.com as well as path ;path=/ ("/" set cookie in whole domain)
document.cookie = cname + "=" + cvalue + "; " + expires +";path=/";
I am having a tough time understanding how I can delete the whole cookie file that the website creates.
I have the cookie at this location
C:\Users\Test\AppData\Local\Microsoft\Windows\INetCache . It is being stored in this format
cookie:Test#TestIdentity.net . Is it possible that I can delete this file using a javascript call.
My website is Test.net but the cookie that is saved is assigned through the Identity provider. So is it going to be an issue accessing the cookie.
I am using this function to iterate over the cookie
function get_cookies_array() {
var cookies = {};
if (document.cookie && document.cookie != '') {
var split = document.cookie.split(';');
for (var i = 0; i < split.length; i++) {
var name_value = split[i].split("=");
name_value[0] = name_value[0].replace(/^ /, '');
cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
}
}
return cookies;
}
var cookies = get_cookies_array();
for (var name in cookies) {
console.log(name + " : " + cookies[name] + " ");
}
This function is only giving me one Cookie but when I programatically check the Request.Cookies collection it has four cookies. I am not sure what I am doing wrong here.
The cookie contains Federation Authentication data.
Thanks
<html>
<head><title></title>
<script type="text/javascript" language="javascript" >
var date = new Date();
date.setTime(date.getTime() + 30000);
document.cookie = "myVar=test; expires=" + date.toGMTString();
alert(document.cookie);
var expires = new Date();
expires.setTime(expires.getTime() - 1000);
document.cookie = "myVar=x; expires=" + expires.toGMTString();
alert(document.cookie);
</script>
</head>
<body>
</body>
</html>
var cookie = cookie_name + "=; expires=" + cookie_date.toGMTString() + "; path=/";
parent.menu.document.cookie = cookie;
In case somebody wonders why IE 11 doesn't delete a cookie, try removing the domain parameter:
// Before:
document.cookie = 'foo=; path=/; domain=example.com; expires=Thu, 01-Jan-1970 00:00:01 GMT'
// After:
document.cookie = 'foo=; path=/; expires=Thu, 01-Jan-1970 00:00:01 GMT'
I am using following function
function setCookie(c_name,value,exdays){
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
setCookie("userName","vimalraj.s",1);
It create cookies in a "session " not with a 24 hours expiry time .
how to fix this ?
UPDATE :
The above code works fine in my colleague's computer Firefox(27.0.1)
and it doesn't for me same Firefox version
I even tried "max-age" instead of "expires"
function set_cookie ( cookie_name, cookie_value,
lifespan_in_days, valid_domain )
{
// http://www.thesitewizard.com/javascripts/cookies.shtml
var domain_string = valid_domain ?
("; domain=" + valid_domain) : '' ;
document.cookie = cookie_name +
"=" + encodeURIComponent( cookie_value ) +
"; max-age=" + 60 * 60 *
24 * lifespan_in_days +
"; path=/" + domain_string ;
}
Nothing worked ...
Taken from quirksmode.org.
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);
}
Here is for one day
createCookie('ppkcookie','testcookie',1)
I suggest you to create a new cookie with same cookie name.
now you can set the new expire.
This will over ride the existing cookie since both are of same name.
Now the new cookie will have the new expires
old cookie
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
new cookie
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
I hope this will help
I'm trying to set a cookie that will expire at the end of the day. I've create this function :
function mnc(cname,cvalue)
{
var now = new Date();
var expire = new Date();
expire.setFullYear(now.getFullYear());
expire.setMonth(now.getMonth());
expire.setDate(now.getDate()+1);
expire.setHours(0);
expire.setMinutes(0);
//alert(expire.toGMTString() + " " + expire.toString());
var expires = "expires="+expire.toString();
alert(expires + "=> now =" + now);
document.cookie = cname + "=" + cvalue + "; " + expires +"; path=/";
}
On Fiddle : http://jsfiddle.net/MYs6b/
So, the alert box show me the good expiration date.
But, if I change the date on my computer by adding 1 or 100 days, i still have the same value in the cookie.
Why? I'm searching since 3 hours and i don't understand...
EDIT :
I've had an alert on "document.cookie" is empty
http://jsfiddle.net/MYs6b/2/
EDIT 2 :
I've add a better example of my problem. It's working on IE and FF but not on chrome :
http://jsfiddle.net/5h87M/1/
Try This: http://jsfiddle.net/MYs6b/1/
function mnc(cname,cvalue)
{
var now = new Date();
var expire = new Date();
expire.setFullYear(now.getFullYear());
expire.setMonth(now.getMonth());
expire.setDate(now.getDate()+1);
expire.setHours(0);
expire.setMinutes(0);
expire.setSeconds(0);
var expires = "expires="+expire.toString();
alert(expires + "=> now =" + now);
document.cookie = cname + "=" + cvalue + "; " + expires +"; path=/";
}
mnc("test", "123456");
Last update of chrome correcting this issue.
function createCookie(name,value,path) {
var expires = "";
var date = new Date();
var midnight = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59);
expires = "; expires=" + midnight.toGMTString();
if (!path) {
path = "/";
}
document.cookie = name + "=" + value + expires + "; path=" + path;
}