Incrementing Cookie Value in Javascript Each Refresh - javascript

I am having an issue where I want a value of my cookie to increase by 1 each time I load the page. Currently, I can get the value to go up by 1, but since the values variable is called at the beginning it continues to reset each visit.
var cName = "Cookie Value";
var cValue = 0, expDays = 10;
let cookies = document.cookie;
function buildCookie(cName, cValue, expDays) {
let date = new Date();
date.setTime(date.getTime() + (expDays * 24 * 60 * 60 * 1000));
const expires = "expires=" + date.toUTCString();
document.cookie = cName + "=" + cValue + "; " + expires + "; path=/";
}
function setToZero() {
buildCookie(cName, cValue=0, expDays);
console.log('Cookie set to 0');
}
function wholePackage() {
if (cookies == null) {
setToZero();
} else {
if (cValue >= 0) {
cValue = cValue + 1;
buildCookie(cName, cValue, expDays);
console.log('Cookie to set to ' + cValue);
}
}
}
wholePackage()
Any help would be appreciated, thank you.

The problem here is that you're resetting the counter on each page load because you don't read the current stored value inside of document.cookie.
You should first read the current value and then increment by 1.
In order to read the current value of a property inside the document.cookie you could do something like this:
const prop = document.cookie.split("; ").map(prop => prop.split("=")).find(prop => prop[0] === cName)
if (prop) {
console.log('Current counter:', prop[1])
}
The code is very naive, but it should give you a starting point.
If it's not clear please let me know.

In wholePackage methods you need to get value of cookie and convert it to number by below code:
+document.cookie.split("; ")[0].split("=")[1]
This is complete code:
var cName = "Cookie Value";
var cValue = 0, expDays = 10;
let cookies = document.cookie;
function buildCookie(cName, cValue, expDays) {
let date = new Date();
date.setTime(date.getTime() + (expDays * 24 * 60 * 60 * 1000));
const expires = "expires=" + date.toUTCString();
document.cookie = cName + "=" + cValue + "; " + expires + "; path=/";
}
function setToZero() {
buildCookie(cName, cValue = 0, expDays);
console.log('Cookie set to 0');
}
function wholePackage() {
if (!cookies) {
setToZero();
} else {
if (cValue >= 0) {
cValue = +document.cookie.split("; ")[0].split("=")[1] + 1;
buildCookie(cName, cValue, expDays);
console.log('Cookie to set to ' + cValue);
}
}
}
wholePackage()

If you want to set cookie value for each time page loads, then the initial value should be 1. Not zero. So, it is not setToZero, it should be setToOne. So set initial cValue = 1.
In the wholePackage function, you are checking if the cValue is greater than or equal to 0. If it's true you are setting the cookie to 0. Which is wrong in two way.
a. cValue is always 0 at the beginning. So it can't get higher.
b. Even somehow you manage to increase cValue (ex- using a database), it is still greater than 0 and making the cookie 0 again.
So, what you need is to check if the cookie exists. If cookie with the name cName exists it will be set to old cookie + 1. Otherwise set to zero.
You can't check cookie value with this code
cookies = document.cookie
Instead, write this function to check if cookie exists,
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
return decodeURI(dc.substring(begin + prefix.length, end));
}
Then the wholePackage function will be like this,
let cookies = getCookie(cName);
function wholePackage() {
if (cookies == null) {
setToOne();
} else {
cValue = cookies + 1;
buildCookie(cName, cValue, expDays);
console.log('Cookie to set to ' + cValue);
}
}
}
In buildCookie function, you can't have parameters' name as same as your previously declared variable. That's bad. cName, cValue is already declared in the beginning.
You don't need expiry date as a parameter as you are creating them inside the function.
Here is the complete fixed code,
var cName = "Cookie Value";
var cValue = 1;
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
return decodeURI(dc.substring(begin + prefix.length, end));
}
let cookies = getCookie(cName);
function buildCookie(cname, cvalue) {
let date = new Date();
date.setTime(date.getTime() + (expDays * 24 * 60 * 60 * 1000));
const expires = "expires=" + date.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/";
}
function setToOne() {
buildCookie(cName, cValue);
console.log('Cookie set to 1');
}
function wholePackage() {
if (cookies == null) {
setToOne();
} else {
cValue = cookies + 1;
buildCookie(cName, cValue);
console.log('Cookie to set to ' + cValue);
}
}
}
wholePackage()

Related

JavaScript: incrementing a cookie value and printing to the console

According to Set cookie and get cookie with JavaScript, the canonical function to set a cookie is:
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=/";
}
I'm trying to modify this function so that it:
a) instantiates a counter variable the first time the page loads
b) increments the counter variable each time the page is refreshed
c) prints the current value of the counter variable to the console
Here is my attempt:
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();
}
else {
expires = "";
}
if (!value) { // should I be checking to see if the COOKIE _itself_ exists? (rather than the value)
var value = 1;
} else {
value++;
}
document.cookie = name + "=" + value + expires + "; path=/";
console.log('Cookie value is', value)
}
### EDIT: ###
Here is a function to get the cookie:
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;
}
EDIT 2
Here is what I'm trying based on one of the suggestions:
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=/";
console.log('Cookie value is', value)
}
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;
}
//setCookie('foo', 3, 5);
//var x = readCookie('foo');
//if (x) {
// console.log('this is foo bar!')
//}
let t = readCookie('foo') || 0;
setCookie('foo', t++, 5);
This results in:
Cookie value is 0
##########################################
Calling setCookie('test', 1, 5) results in:
Cookie value is 2
I get a value of 2 even when loading the page for the first time (presumably because there is a numerical value passed for value when the function is called).
Should I be checking to see if the cookie itself exists (rather than a numerical value for the value argument)?
I would greatly appreciate any assistance with implementing a, b, and c above.
Thanks!

Is this javascript code valid? And is it efficient? Trying to create a javascript user ID and a session ID

Im trying to create my own analytics script for my website, and for this I have tried to put together a way to create userID and sessionID.
But I am not sure if I have done it correctly.
I'm trying to:
Check to see if user has set a userID - if not set it.
check to see if user has a sessionID - it not set it.
the userID is set to follow the user, where the user continues to hold the userID on several visits, where the sessionID is unique for each visit.
if (getCookie('yb_uid') != null) {
if (getCookie('yb_sid') != null) {
setCookie('yb_uid', getCookie('yb_uid'), 730);
setSessionCookie(getCookie('yb_sid'));
} else {
setCookie('yb_uid', getCookie('yb_uid'), 730);
setSessionCookie(setSID());
}
} else {
setCookie('yb_uid', setUID(), 730);
setSessionCookie(setSID());
}
if (getCookie('yb_sid') == null || getCookie('yb_sid') ==
'undefined' || !getCookie('yb_sid')) {
setSessionCookie(setSID());
}
function setUID() {
return "ybID#" + _setID(5) + "-" + _setID(5) + "-" + Date.now();
}
function setSessionCookie(value) {
var now = new Date();
var minutes = 30;
now.setTime(now.getTime() + (minutes * 60 * 1000));
document.cookie = "yb_sid=" + value + "; max-age=" + now.toUTCString() + "; expires=" + now.toUTCString() + "; path=/";
} /*set session cookie*/
function getCookie(name) {
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
} /* get cookie value */
function _setID(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
function setSID() {
var ts = Math.round(+new Date() + Math.random() / 1000);
return ts;
}
function setCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
var expires = "; max-age=" + date.toGMTString() + " expires=" + date.toGMTString();
} else {
var expires = "";
}
document.cookie = name + "=" + value + expires + ";path=/";
Maybe this has an even easier way to script it?
Have you tried UUID https://www.npmjs.com/package/uuid for generating an user id?

Have my page display cookie information, when certain actions will set a cookie

Is there a way to have my page continuously monitor for a cookie in realtime with Javascript, and if the cookie ever is set then it will send an alert?
The part that I don't understand is how do you check for the cookie in realtime? For example, a user might click a checkbox, a cookie will get set, and then the page to "see" that the cookie is now set and trigger an alert, all in real-time without delay.
Here's an example (not written correctly) that kinda shows what I'm going for.
<div id="click" onclick="setcookie()"></div>
<script>
function checkcookie() {
if (cookie_exists)
alert('cookie exists')
}
</script>
The part that I don't understand is how do I get checkcookie() function to continuously be monitoring for the existence of the cookie I just set with my click?
You have to implement an interval timeout to continuously check for a cookie's value.
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
// because unescape has been deprecated, replaced with decodeURI
//return unescape(dc.substring(begin + prefix.length, end));
return decodeURI(dc.substring(begin + prefix.length, end));
}
// Method used for continuously monitoring a cookie
function monitorCookie(cookieName) {
setInterval(function() {
var cookieValue = getCookie(cookieName);
console.log('Yummy Cookie =' + cookieValue);
}, 500);// monitor cookie every 500 miliseconds.
}
$(document).ready(function() {
monitorCookie("YummyCookie");
});
The only way is to use
window.setInterval("CheckCookie()", 1000);
Which checks for cookie every second
Here are basic functions for writing and reading cookies:
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 = '/';
}
function getCookie(cname) {
var name = cname + '=';
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 null;
}
function checkCookie(cname) {
var cookie = getCookie(cname);
if (cookie != null) {
return true;
} else {
return false;
}
}
function remove_cookie(cname) {
document.cookie = cname + '=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;'
}
from w3schools.com/js/js_cookies.asp

Javascript Cookie define Path

So I am new to JavaScript and I'm kinda stuck.
I want to allow my cookie to work on all of my pages.
I know that I need to add "/" to path. The only problem is that the little script I got is a bit different than all the examples out there.
Does somebody know where to put it?
var expdate = new Date();
expdate.setTime(expdate.getTime() + (24 * 60 * 60 * 1000 * 365));
function setCookie(name, value, expires, path, domain, secure) {
var thisCookie = name + "=" + escape(value) + ((expires) ? "; expires=" +
expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ((secure) ? "; secure" : "");
document.cookie = thisCookie;
}
function showCookie() {
alert(unescape(document.cookie));
}
function getCookieVal(offset) {
var endstr = document.cookie.indexOf(";", offset);
if (endstr == -1) endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function GetCookie(name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) return getCookieVal(j);
i = document.cookie.indexOf(" ", i) + 1;
if (i === 0) break;
}
return null;
}
function MyNamer() {
var now = new Date();
now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
var username = GetCookie("username");
if ((!username) || (username == 'null')) {
username = prompt("What is your name?:", "");
}
setCookie("username", username, now);
if (username) {
document.write(username);
setCookie("username", username, now);
} else
document.write("Guest")
}
Thanks in advance!
Well, from your code it looks like the 4th argument in setCookie is the one you want:
setCookie(name, value, expires, path, domain, secure)
e.g.setCookie("myCookie", "myCookieValue", new Date(), "/")
What are you using the cookie for? The webserver you're making the request from controls cookie data, including path. If you're just storing data then you could use the browsers' local/session storage objects?

Delete Existing Cookies

I used the following JavaScript to create a pop-up window on the website and for it to show up only once. Now, my client wants a new promotion and I am trying to delete existing cookies and make it pop-up again (so that people who already visited the website, see the pop-up window again, only once like before). Here is the current code:
<!--
function setCookie(name, value, expires, path, domain, secure) {
var curCookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
document.cookie = curCookie;
}
function setCookie(name, value, expires, path, domain, secure) {
var curCookie = name + "=" + escape(value) +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "") +
((expires) ? "; expires=" + expires.toGMTString() : "") ;
document.cookie = curCookie;
}
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
} else
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1)
end = dc.length;
return unescape(dc.substring(begin + prefix.length, end));
}
function pop()
{
$(document).ready(function() {
$('#myModal').reveal();
});
}
var seen = getCookie("seen");
if (!seen) {
var now = new Date();
now.setTime(now.getTime() + 360000 * 1000);
setCookie("seen", 1, now);
pop();
}
//-->
I tried the following to reset the cookies
<!--
function setCookie(name, value, expires, path, domain, secure) {
var curCookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
document.cookie = curCookie;
}
function setCookie(name, value, expires, path, domain, secure) {
var curCookie = name + "=" + escape(value) +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "") +
**";expires=Thu, 01 Jan 1970 00:00:01 GMT";**
document.cookie = curCookie;
}
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
} else
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1)
end = dc.length;
return unescape(dc.substring(begin + prefix.length, end));
}
function pop()
{
$(document).ready(function() {
$('#myModal').reveal();
});
}
var seen = getCookie("seen");
if (!seen) {
var now = new Date();
now.setTime(now.getTime() + 1 * 1000);
setCookie("seen", 1, now);
pop();
}
//-->
It's not working. I'm new to JavaScript and would appreciate your help!
I see you have a nice mess so, if I have understood well, this code should do the job:
// on document ready
$(function(){
// check for the old cookie and delete it
if( Cookies.Check('seen') ) Cookies.Set('seen', '', -1); // delete the cookie if it exists
// now work with a new one with other name
if( !Cookies.Check('newmodal') ){ // if the cookie doesn't exist we show the modal and set the cookie
$('#myModal').reveal();
Cookies.Set('newmodal', 'true', 365); // days, if you need to use minutes see the method below
} // there is no `else` here, if the cookie exists nothing happens
});
/**
* Object with methods to manage cookies
* #type Object
*/
var Cookies = {
/**
* Checks if a cookie exists
* #param {String} name
* #return Boolean
*/
Check: function (name) {
return !!this.Get(name);
},
/**
* Gets a cookie value or returns false
* #param {String} name
* #return String|Boolean
*/
Get: function (name) {
var n, ca, c;
n = name + "=";
ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
c = ca[i].trim();
if (c.indexOf(name) === 0) return c.substring(name.length + 1, c.length);
}
return false;
},
/**
* Sets a cookie
* #param {String} name
* #param {String} value
* #param {Number} [expire]
* #param {Object} [options]
* #return Boolean|void
*/
Set: function (name, value, expire, options) {
var d = new Date(), expires;
var defaults = { expire_in: 'days', path: '/' };
if (typeof options !== "undefined") $.extend(true, defaults, options);
if (expire !== undefined && expire !== null) {
if (defaults.expire_in == 'days') d.setDate(d.getDate() + expire);
else if (defaults.expire_in == 'minutes') d.setDate(d.getTime() + expire * 1000);
else {
throw new JUtils.EX('expire_in configuration is not valid');
}
expires = "expires=" + d.toGMTString();
}
else expires = expires = "";
document.cookie = name + "=" + value + "; " + expires + '; path=' + defaults.path;
return true;
}
};

Categories