How to remove PHP cookie in JavaScript? [duplicate] - javascript
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=/";
Related
Cannot set cookie to expire on browser close
I'm trying to set a cookie using javascript so it expires when the browser is closed. I have the following function to do that: function createCookie(value,days) { var name = "name"; var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days*24*60*60*1000)); expires = "; expires=" + date.toUTCString(); } var cookie = name + "=" + value + expires + "; path=/"; document.cookie = cookie; } I tried many ways found here and there on the web like setting the date to "", setting it to yesterday (in that case the cookie is not even added) and omitting "expires" completly. I tried on Firefox and Chrome checking that every process was stopped before opening again, but the cookie is alway there. What am I missing?
I am using this function for my self. It will work for you i gess :) function createCookie(name, value, expiresInX_days, path) { var a = new Date; var expires = expiresInX_days || 1; a.setTime(Date.now() + (1000 * 60 * 60 * 24 * expires)); var pt = path ? " ; path=" + path + ";" : ";"; return (document.cookie = name + "=" + value + ";" + "expires=" + a.toUTCString() + pt) ? !0 : !1; }
If you want to delete your cookie, you can use this: function rmCookie(cookieName){ var a = new Date; a.setTime(0); return (document.cookie = cookieName + "=;" + a.toUTCString()) ? !0 : !1; } If you want get your cookie clean, function getMyFuckingCookie(cookieName){ var a = document.cookie.replace(/; /g, ";").split(";"), b = a.length, c = {}, nm = cookieName || !1; while (b--) { var d = a[b].split(/=(.+)/); c[d[0]] = d[1]; } return (nm) ? c[nm] : c; }
Set Expires Time in Cookie Javascript
I have a string that I use to set expires date in cookie. But I always fail to set it. Here is my Code: var expTime = '2016-06-09T03:06:53Z'; var valueCookie = 'test'; SetCookie('myCookie', valueCookie, expTime); function SetCookie(name, value, expTime) { document.cookie = name + '=' + value + '; ' 'expires=' + expTime+ '; path=/'; }; Why I fail to set Expire Date in Cookie? Thanks
try this 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 parameters of the function above are the name of the cookie (cname), the value of the cookie (cvalue), and the number of days until the cookie should expire (exdays). The function sets a cookie by adding together the cookiename, the cookie value, and the expires string.
here is my code function setCookie(name,value,data){ var oDate =new Date(); oDate.setDate(oDate.getDate()+data); document.cookie=name+'='+value+';expires='+oDate; }
I think there is a syntax error.Try this var expTime = '2016-06-09T03:06:53Z'; var valueCookie = 'test'; SetCookie('myCookie', valueCookie, expTime); function SetCookie(name, value, expTime) { document.cookie = name + '=' + value + '; expires=' + expTime+ '; path=/'; }
Not able to set cookies secure and HttpOnly properties
For whatever reason when I try to set the secure and HttpOnly properties through Javascript, they fail to get set. Here is the code that is being used: function Selected(StationID,QueryString) { ClearColours(); document.getElementById(StationID).className='StationSummary_Container_Selected'; setCookie('selectedItem',StationID,1); setCookie('selectedItemValue',StationID,1); setCookie('selectedItemQString',QueryString,1); window.location="#" + StationID; parent.frames["stationDetail"].location = "StationDetail.aspx?" + QueryString; parent.frames["message"].location = "StationMessage.aspx?" + QueryString; } function setCookie(NameOfCookie, value, expiredays) { var ExpireDate = new Date(); ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000)); var newCookie = NameOfCookie + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString()) + "; Secure; HttpOnly"; document.cookie = newCookie; } Thanks in advance for any tips on this.
The browser does not allow you to read or write HttpOnly attribute using JavaScript for security reasons. The clue is in the name, I guess: HttpOnly. You can set these attributes on the server if you need to.
Deleting a cookie with an onclick event
My script sets a cookie named stop_mobi with JavaScript. I am then trying to delete the cookie when a user clicks a link with an onclick event however when I test this the cookie is not deleted. Any pointers to where I am going wrong would be greatly appreciated. Thanks. <script type="text/javascript"> // set stop_mobi cookie for test purposes function setCookie(cookieName, cookieValue, nDays) { var today = new Date(); var expire = new Date(); if (nDays == null || nDays == 0) nDays = 1; expire.setTime(today.getTime() + 3600000 * 24 * nDays); document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString(); } setCookie("stop_mobi", "yes", "5"); function deleteCookie(name) { document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; alert('Cookie deleted'); } </script> Delete cookie
How to delete a cookie?
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=/";