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;
}
Related
I'm trying to set cookies that are permanent in Microsoft edge. They last only until I close the browser. Yes I have cookies enabled. Here is some code I found from a while ago:
var cookieHandler = {
setCookie : function(name, value, days, time)
{
var expires = "";
if(days)
{
var date = new Date();
date.setTime(date.getTime() + (time || (days * 24 * 60 * 60 * 1000)));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
},
getCookie : function(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;
},
eraseCookie : function(name)
{
document.cookie = name + '=; Max-Age=-99999999999;';
}
};
Yeah when I reopen the browser my cookies are gone. Does anyone have working code for cookies in Microsoft edge?
Edit:
I'm using the file:/// origin.
I wrote a script in javascript to delete all cookies (except some included in a whitelist) within the current domain (using document.cookie). How can I make sure that it is working and indeed deleting the cookies?
I ran it in the browser by including it in an html file and then opening that file, but I don't understand how to test that it will delete cookies within the domain since when I open an html file it is not associated with a domain.
Here is my code:
//cookies we need
const whitelist = [
'example_cookie',
];
function removeUnnecessaryCookies() {
let decodedCookie = decodeURIComponent(document.cookie); //check for special characters
let allCookies = decodedCookie.split(';'); //make array of all cookies in domain
for (var i = 0; i < allCookies.length; i++) {
let cookie = allCookies[i];
if (!whitelist.includes(cookie)) {
deleteCookie(cookie);
}
}
}
/* helper function to delete cookies */
function setCookie(cookieName, cookieValue, cookieExpiry) {
let date = new Date();
date.setTime(date.getTime() + (cookieExpiry*24*60*60*1000));
let expires = "expires=" + date.toUTCString();
document.cookie = cookieName + "=" + cookieValue + ";" + expires + ";path=/";
}
function deleteCookie(cookieName) {
setCookie(cookieName, '', -100);
}
removeUnnecessaryCookies();
Write a getCookie method and test for that. Here is an example:
function setCookie(name, value, days) {
var expiry = new Date()
expiry.setTime(expiry.getTime() + (days * 24 * 60 * 60 * 1000))
var expires = 'expires=' + expiry.toUTCString()
document.cookie = name + '=' + value + ';' + expires + ';' + 'path=/'
}
function getCookie(name) {
var name = name + '='
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 false
}
// set cookie
setCookie('mycookie', '1', 365);
// get cookie
getCookie('mycookie');
getCookie('joe'); // returns false
Your best bet would be to spin up a localhost webserver (something like WAMP or MAMP or Mac should do the trick) and drop a cookie. Look at the domain in your browser and copy that.
I want to apply css through javascript if cookie xxxexist - code:
<script>
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 + ";path=/";
}
var kuki = document.cookie.indexOf('cookie_name=xxx');
alert(kuki);
if (kuki != -1)
{
document.getElementById("ads-back").style.display = "none";
document.getElementById("ffield").style.display = "none";
document.getElementById("bcd").style.display = "none";
}
else { setCookie(xxx, 1, 1) }
</script>
The problem is that I always receiving -1 it should after seting cookie setCookie(xxx, 1, 1) get different value?
setCookie(xxx, 1, 1)
As you are setting cookie name with xxx variable and finding it with cookie_name as below that is the issue..try to find the index of cookie actual name set then it will work.
var kuki = document.cookie.indexOf('cookie_name=xxx');
To save cookie you have to use following format
document.cookie = cname + "=" + cvalue + ";expires=" + expires + ";";
To get saved cookies you have to use following both ways because if you have saved more than one cookie your cookie may not be the first element of the cookie array so you have to check both 'cookie_name=xxx' and
' cookie_name=xxx'
var kuki1 = document.cookie.indexOf('cookie_name=xxx');
var kuki2 = document.cookie.indexOf(' cookie_name=xxx');
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);
}
}
}
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);