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=/";
Set Cookie function in Jquery
function setCookie(cookieName, cookieValue, cookieExpireDays) {
var d = new Date();
d.setTime(d.getTime() + (cookieExpireDays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cookieName + "=" + cookieValue + ";" + expires + ";" + "path=/";
}
Delete function in Jquery
function deleteCookie(name) {
var domain = location.hostname,
path = '/'; // root path
document.cookie = [
name, '=',
'; expires=' + new Date(0).toUTCString(),
'; path=' + path,
'; domain=' + domain
].join('');
}
This works fine for local links, but when I try to use it on external websites. I can get my document.cookie but deleteCookie function does not delete the cookie. Any ideas?
*Please remember, I am just running these scripts from console of Google Chrome
I might be misunderstanding something in your question, but here's how I handled the getting, setting, and deleting of a cookie I set.
fiddle: https://jsfiddle.net/hmvyu3L6/
<button class='set'>set</button>
<button class='get'>get</button>
<button class='delete'>delete</button>
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;
}
function getCookie(cname) {
var name = cname + '=',
ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length,c.length);
}
}
return '';
}
function deleteCookie( name ) {
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
var value = 'hey there';
$('.set').on('click', function() {
setCookie('testCookie', value, 360);
});
$('.get').on('click', function() {
console.log(getCookie('testCookie'));
});
$('.delete').on('click', function() {
deleteCookie('testCookie');
});
If the cookies are HttpOnly, you will not be able to delete them using javascript or jquery.
Make sure your domain and path match exactly. If they are different (e.g. .subdomain.domain.com instead of .domain.com, or /path instead of /) then the script will not affect the cookies.
Alright, I am answering my own question because I changed few things and it works now.
var domain = location.hostname
function setCookie(cookiename, cookievalue, expiredays, domain) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expiredays=" + date.toGMTString();
document.cookie = cookiename+ "=" + cookievalue+ expires + "; domain=" + domain + "; path=/";
}
function deleteCookie(cookiename, domain) {
setCookie(cookiename, "", -1, domain);
}
deleteCookie("Cookie_Name",domain)
I am using the functions, SET/Get and check cookie.
The getCookie function, splits the cookie by using(';') it works fine unless I want to save some text which has (';') inside by cookie.
The split function splits the content incorrectly based on (';').
When I change that to something else like ('&') it does not save at all!
Can anyone give an idea what can I use for that?
function setCookie(content, player) {
var d = new Date();
d.setTime(d.getTime() + (365 * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = player + "=" + content + "; " + expires;
}
//check if the coockie with current player name exists
function checkCookie(player_name) {
var pnote = getCookie(player_name);
alert(pnote);
var delete_cookie = function (player_name) {
document.cookie = player_name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};
if (pnote != "") {
$('#tab' + player_name + ' .nicEdit-main').html(pnote);
} else {
if (player_name != "" && player_name != null) {
$('#tab' + player_name + ' .nicEdit-main').prepend("no note");
}
}
}
//Gets the cookie content
function getCookie(player_name) {
var name = player_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);
if (c.indexOf(name) == 0)
return c.substring(name.length, c.length);
}
return "";
}
in setCookie use escape function :
document.cookie = player + "=" + escape(content) + "; " + expires;
and in getCookie use unescape function
return unescape(c.substring(name.length, c.length));
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;
}
I am trying to save cookies in JavaScript and then display them on the page again but for some reason my setCookies function and displayCookies function is not working properly.. I want it to also expire after 1 week. It is coming from a form and when I put it in Web Developer in FireFox it says Reference Error setCookies and displayCookies is not defined. My jsfiddle is : http://jsfiddle.net/FmXJW/
function setCookies()
{
// this function will set cookies for each field in the reservation form, and set them to expire after one day
var Name = document.forms[0].txtName.value;
var Address = document.forms[0].txtAddress.value;
var City = document.forms[0].txtCity.value;
var State = document.forms[0].txtState.value;
var Zip = document.forms[0].txtZip.value;
var Email = document.forms[0].txtEmail.value;
var CarType = document.forms[0].txtCarType.value;
var PickupDate = document.forms[0].txtPickupDate.value;
var ReturnDate = document.forms[0].txtReturnDate.value;
var myDate = newDate();
myDate.setDate(myDate.getDate() + 7);
document.cookie = "name=" + encodeURIComponent(Name) + "; expires=" + myDate.toUTCString();
document.cookie = "address=" + encodeURIComponent(Address) + "; expires=" + myDate.toUTCString();
document.cookie = "city=" + encodeURIComponent(City) + "; expires=" + myDate.toUTCString();
document.cookie = "state=" + encodeURIComponent(State) + "; expires=" + myDate.toUTCString();
document.cookie = "zip=" + encodeURIComponent(Zip) + "; expires=" + myDate.toUTCString();
document.cookie = "email=" + encodeURIComponent(Email) + "; expires=" + myDate.toUTCString();
document.cookie = "carType=" + encodeURIComponent(CarType) + "; expires=" + myDate.toUTCString();
document.cookie = "pickupDate=" + encodeURIComponent(PickupDate) + "; expires=" + myDate.toUTCString();
document.cookie = "returnDate=" + encodeURIComponent(ReturnDate) + "; expires=" + myDate.toUTCString();
window.alert ("Your reservation has been saved.");
} // end function setCookies()
function displayCookies()
{
// this function will read the saved cookies, and repopulate the form with the cookie values
var cookieString = decodeURIComponent(document.cookie);
var cookieArray = cookieString.split("; ");
if (document.cookie == 0)
{
alert("You have not made a reservation");
}
else
{
// retrieve each cookie, and display the cookie value in the appropriate form field
document.forms[0].txtName.value = cookieArray[0].lastIndexOf("=") + 1);
document.forms[0].txtAddress.value = cookieArray[1].lastIndexOf("=") + 1);
document.forms[0].txtCity.value = cookieArray[2].lastIndexOf("=") + 1);
document.forms[0].txtState.value = cookieArray[3].lastIndexOf("=") + 1);
document.forms[0].txtZip.value = cookieArray[4].lastIndexOf("=") + 1);
document.forms[0].txtEmail.value = cookieArray[5].lastIndexOf("=") + 1);
document.forms[0].txtCarType.value = cookieArray[6].lastIndexOf("=") + 1);
document.forms[0].txtPickupDate.value = cookieArray[7].lastIndexOf("=") + 1);
document.forms[0].txtReturnDate.value = cookieArray[8].lastIndexOf("=") + 1);
}
} // end function displayCookies()
You have a couple of problems on your code:
You are not retrieving the value from the different fields stored on the cookie correctly, you need to use slice to get the right part.
I also guess the line var myDate = newDate(); should be var myDate = new Date();.
I have changed your fiddle (find it here) and loaded the code in <head> and now it seems to save and display the cookies correctly.