Fiddle
Cookies.setCookie("x", "42");
var x = Cookies.getCookie("x");
alert("Meaning of life = " + x);
// BUG: This line does not in fact clear the cookie. Why?
Cookies.clearCookie("x");
x = Cookies.getCookie("x");
alert("Life should have no meaning : " + x);
And the Cookies code:
// This actually appears above, don't worry about undefined Cookies
Cookies = new function() {
var self = this;
self.getCookie = function(c_name, opt_domain) {
var i, name, value, cookies=document.cookie.split(";");
for (i=0; i < cookies.length; i++) {
name = cookies[i].substr(0, cookies[i].indexOf("="));
value = cookies[i].substr(cookies[i].indexOf("=")+1);
name = name.replace(/^\s+|\s+$/g,"");
if (name==c_name) {
if (opt_domain) {
if (!(value && value.indexOf(";domain=" + opt_domain) != -1)) {
continue;
}
}
return decodeURIComponent(value);
}
}
return null;
};
self.setCookie = function(c_name, value, opt_exdays, opt_domain) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + opt_exdays);
if (!opt_domain) {
opt_domain = document.domain;
}
var c_value = encodeURIComponent(value) + (opt_exdays? "; expires=" + exdate.toUTCString() : "") + ";path=/" + (opt_domain ? ";domain=" + opt_domain : "");
document.cookie=c_name + "=" + c_value;
};
self.clearCookie = function(c_name) {
// http://blogs.x2line.com/al/articles/316.aspx
var d = new Date(0).toUTCString();
document.cookie = c_name + "=deleted;expires=" + d + ";path=/";
};
};
I don't know for sure what the issue is with your code (it may be because you aren't setting at least the path), but according to this reference, an easier way of removing a cookie value is like this:
self.clearCookie = function(c_name) {
self.setCookie(c_name, "", -1);
}
It is because the domain is not specified.
If you change clearCookie to:
self.clearCookie = function(c_name) {
// http://blogs.x2line.com/al/articles/316.aspx
var d = new Date(0).toUTCString();
document.cookie = c_name + "=deleted;expires=" + d + ";path=/;domain=" + document.domain;
};
It clears the cookie (using document.domain).
Alternatively you can just call:
this.setCookie(c_name, "", -1);
Related
Below are the two functions I currently use inorder to read and create my cookie (cookie should only be valid for 1 day)
function set1DayValidationCookie(){
var d = new Date();
var today = d.getMonth() + '' + d.getDate();
if (readCookie('onedaycookie') != today) {
document.cookie = 'onedaycookie='+today;
console.log('cookie has been created');
} else {
alert('cookie already exist!');
}
}
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;
}
On refresh of the page, cookie is recognized however
for example, I change my url from www.mywebsite.com/en/ to www.mywebsite.com/ru/
(for language purposes) cookie has been created again.
I would like to ask what I am missing on this part?
You need to set the 'path' part of the cookie to '/'. Then it will Work for all paths.
document.cookie = "username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
Witout the path, the cookie will be set for the current path only.
I would suggest this code
window.cookie = {
set: function(c_name, value, exdays, path = '/') {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : ("; expires=" + exdate.toUTCString())) + "; path=" + path;
document.cookie = c_name + "=" + c_value;
},
get: function(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
};
And you can check like this:
if("undefined" !== typeof cookie.get('lang')){
//cookie is not set
cookie.set('lang', 'en', 1);
}else{
//cookie is set
}
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;
}
What i am trying to accomplish :
When a href is pressed i call the saveItem() function. It is called as below :
<a href="#" class="save-product" onclick="saveItem('savedList', '<?php echo get_the_ID();?>', 90)">
savedList = the name of my cookie
get_the_ID() = A wordpress function to get the current's ID post, '185' etc.
90 = the days for the cookie to expire
When saveItem() is called, it checks if a cookie with name savedList already exists. If it doesn't, it creates a cookie with that name and adds the value which is passed through the parameter(the id of current post).
When this cookie exists, i want to add to that cookie one more id and the delimiter would be ; so i can - in another page show a list of products through that cookie's list.
So my cookie has "185" . When i add a new ID, for example "65", i want my cookie to become "185;65"
My problem is that it doesn't work as expected. The weird thing is that if i see on the console.log("New Value Is : " + newValue); it shows "185;65" but
console.log(mNameList); shows only "185" again.
To check my cookie's value i use :
print_r($_COOKIE['savedList']);
Functions below :
saveItem():
function saveItem(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
// Get Cookie
var mNameList = getCookie(name);
// If cookie is empty - doesn't exist then create it and put the value given
if (mNameList == "") {
document.cookie = name + "=" + value + expires + "; path=/";
} else {
// If cookie exists, check if it has already this value, if it doesn't then add oldvalue + new value to that cookie.
if(mNameList !== value){
var newValue = mNameList + ';' + value; // "185;65"
document.cookie = name + "=" + newValue + expires + "; path=/";
console.log("New Value Is : " + newValue);
var mNameList = getCookie(name); // Το check current cookie get it again
console.log(mNameList); // Show it - here it shows "185"
}
else{
// Value already exists in cookie - don't add it
console.log("Are same - mNameList->" + mNameList + " | currentID->" + value);
}
}
}
Getcookie();
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 "";
}
As you do it yourself ; is the field delimiter in a cookie between value, expiration etc. You cannot use it to seperate your values.
Ok so the problem was in the delimiter and in my code too - the way i was checking if ID already exists was wrong but the below works.
saveItem()
function saveItem(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
var mNameList = getCookie(name);
if (mNameList == "") {
document.cookie = name + "=" + value + expires + "; path=/";
} else {
var doesItemExists = false;
var partsOfStr = mNameList.split('-');
for(var i =0; i < partsOfStr.length; i++){
if(partsOfStr[i] == value)
doesItemExists = true;
}
if(!doesItemExists){
var newValue = mNameList + '-' + value;
document.cookie = name + "=" + newValue + expires + "; path=/";
console.log("New Value Is : " + newValue);
}
else{
console.log("Are same - mNameList->" + mNameList + " | currentID->" + value);
}
}
}
I am using the following code to set cookie, however, when I use document.cookie in console, it doesn't print the key-value pair I passed via setItem(). Anybody know what is the matter?
var docCookies = {
getItem: function (sKey) {
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sProperties) {
var cookieString = "";
var sExpires = "";
for (var sKey in sProperties){
console.log("inside for");
if (sProperties.hasOwnProperty(sKey)) {
// alert("Key is " + k + ", value is" + target[k]);
console.log("inside if");
cookieString += encodeURIComponent(sKey) + "=" + encodeURIComponent(sProperties[sKey])+"; ";
}
}
console.log("outside for");
document.cookie = cookieString.substring(0,cookieString.length-2);
return true;
},
hasItem: function (sKey) {
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
}
};
var expireDate = (new Date((new Date()).getTime() + (60*24*60*60*1000))).toUTCString();
var sProperties = [];
sProperties['_country'] = _country ;
sProperties['_language'] = _language ;
sProperties['_pageName'] = _pageName ;
sProperties['_products'] = _products ;
sProperties['_events'] = _events ;
sProperties['_server'] = _server ;
sProperties['_href'] = _href ;
sProperties['expires'] = expireDate ;
docCookies.setItem(sProperties);
the cookie you want to save should be an Object
var sProperties = {};
Below is the code I am writing to set the cookie with domain name= “.example.com” but this isn’t working. Any idea what’s wrong with the code? However if I remove the domain name, it works fine.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function setCookie(c_name,value,exdays)
{
alert("Cookie = " + document.cookie);
var c_value=escape(value);`enter code here`
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = c_name +"=" + value + ";expires=" + myDate + ";domain=.example.com;path=/";
}
</script>
</head>
<body onload="setCookie('name','value')">
</body>
</html>
Try these functions. It might help ;)
cookie_create = function (name,value,days) {
var expires, date;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
expires = date = null;
};
cookie_read = function (name) {
var nameEQ = name + "=",
ca = document.cookie.split(';'),
len = ca.length,
i, c;
for(i = 0; i < len; ++i) {
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);
}
nameEQ = name = ca = i = c = len = null;
return null;
};
cookie_erase = function (name){
cookie_create(name,"",-1);
name = null;
};
try this
function setCookie(name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires : "") +
((path) ? "; path=" + path : "; path=" + "/") +
((domain) ? "; domain=" + domain : "; domain=.example.com") +
((secure) ? "; secure" : "");
}