Add a value to a cookie with expiration data? - javascript

How can I add a cookie which expires in 2 months to 'test#gmail.com' from the following code
<div id="home">
<div class="name" my-data="123">Email: test#gmail.com</div>
</div>
I think the code for the actual time should be as follows but I do not know how to add the value to it:
function myemail () {
var expiryDate = new Date();
expiryDate.setMonth(expiryDate.getMonth() + 2);
document.cookie = cookieName + '=y; expires=' + expiryDate.toGMTString

Assuming you have privileges to add an ID to your div, the following code works fine
<body>
<div id="home">
<div class="name" my-data="123" id="email-div">Email: test#gmail.com</div>
<button onclick="myemail()">Set it</button>
</div>
<script>
function myemail() {
var expiryDate = new Date();
var email = document.getElementById("email-div").textContent.split("Email:")[1]
expiryDate.setMonth(expiryDate.getMonth() + 2);
document.cookie = 'emailCookie=' + email + ';expires=' + expiryDate.toGMTString() + ';path=/';
}
</script>
</body
Well I have used a button to trigger the action. You can do the same in any event.

toGMTString is a function, you need to call.
Replace expiryDate.toGMTString to expiryDate.toGMTString()
const Cookie = {
get: function (name) {
const nameEq = name + "=";
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let 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;
},
set: function (name, value, hours) {
const expires = "";
if (hours) {
let date = new Date();
date.setTime(date.getTime() + (hours * 60 * 60 * 1000));
const expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
};
You can change hours to whatever and of course
this one date.setTime(date.getTime() + (hours * 60 * 60 * 1000)); to the corresponding formula
Usage`
Set: Cookie.set('myemail', 'test#gmail.com', 1460) // 1460 is 2 months in hours
Get: Cookie.get('myemail')
const email = document.getElementsByClassName('name')[0].textContent.split(' ')[1]; Cookie.set('myemail', email, 1460);

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?

Cookie based 4 day timer and then redirect Javascript

I am trying to create a Cookie based redirection that takes someone to a new page once 4 days are passed.
I am expecting my site visitors to visit the promo offer page at least 7 times in the first 10 days so I need to make sure that the Cookie is generated for at least 30 days and the timer starts dynamically on their first visit.
Right now I only have this code and looking to get some help!
<script>
$(document).ready(function() {
if (getCookie('cookiesSet') == "") {
setCookie('cookiesSet', 'yes', 365);
setCookie('passed4days', 'no', 4);
} else if (getCookie('passed4days') == '')
window.location = 'www.facebook.com';
});
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 "";
}
</script>
Snippet style as expected:
$(document).ready(function () {
var firstVisitTime = getCookie('firstVisitTime')
if (firstVisitTime != '') {
var soManyDays = ((new Date()).getTime() - firstVisitTime) / (24 * 60 * 60 * 1000)
if (soManyDays > 4) window.location = 'www.stackoverflow.com'
else if (soManyDays > 24) console.log('I should remember you')
} else setCookie('firstVisitTime', (new Date()).getTime(), 366)
})

Create and Delete cookies for external websites on their subdomain

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)

Cookie expiration date

I am not a programmer. I am trying to use a cookie script that remembers the last drop down menu selection.
I found a script that works but it does only a session cookie. How do I add an expiration date to the cookie in this script?
<head>
<script>
function SETcookie() {
document.cookie = "Selected=" + document.getElementById('myList').selectedIndex;
}
function GETcookie() {
if (document.cookie) {
eval(document.cookie);
document.getElementById('myList').selectedIndex = Selected;
}
}
</script>
</head>
<body onLoad="GETcookie()">
<select id="myList" onChange="SETcookie()">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
</body>
Try this:
function setCookie(c_name,c_value,exdays) {
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
document.cookie=encodeURIComponent(c_name)
+ "=" + encodeURIComponent(c_value)
+ (!exdays ? "" : "; expires="+exdate.toUTCString());
;
}
c_name is the name of the cookie
c_value is the cookie value
exdays is the number of days you want the cookie to expire after
Source: http://www.w3schools.com/js/js_cookies.asp
May be this will help
document.cookie = "coolName"+ "=" +"coolValue"+ ";" + "expires="+ new Date(new Date().getTime()+60*60*1000*24).toGMTString()+";path=/";
Here's function which is 100% working and has no depreciated functions.
function setCookie(variable, value, expires_seconds) {
var d = new Date();
d = new Date(d.getTime() + 1000 * expires_seconds);
document.cookie = variable + '=' + value + '; expires=' + d.toGMTString() + ';';
}
try
var a = new Date();
a = new Date(a.getTime() +1000*60*60*24*365);
document.cookie = 'mycookie=somevalue; expires='+a.toGMTString()+';';
PS. The value 1000*60*60*24*365 = 1 Year
To Get the selected index try this GETcookie:
function GETcookie(){
if (document.cookie){
var a = document.cookie;
Selected = a.substring(a.search('Selected=')+9,a.search(';'));
alert("Selected = " + Selected);
document.getElementById('myList').selectedIndex=Selected;
}}
;max-age=max-age-in-seconds (e.g., 606024*365 or 31536000 for a year)
;expires=date-in-GMTString-format If neither expires nor max-age specified it will expire at the end of session.
document.cookie = "doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; SameSite=None; Secure";
know more
You could try this:
function SETcookie(){
var validity_days = 7;
var expires = validity_days * 1000 * 60 * 60 * 24;
var expires_date = new Date( today.getTime() + (expires) );
document.cookie="Selected="+document.getElementById('myList').selectedIndex + ";expires=" + expires_date.toGMTString() + ";";
}
This is for setting the expiry date in terms of days(5 days here)
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
var expires = "expires="+d.toUTCString();
}
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 "";
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
//your code goes here
} else {
//your code goes here
if (user != "" && user != null) {
setCookie("username", user, 5);
}
}
}
This is for setting the expiry date in terms of minutes(5 minutes here)
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + exdays * 60 * 1000);
var expires = "expires="+d.toUTCString();
}
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 "";
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
//your code goes here
} else {
//your code goes here
if (user != "" && user != null) {
setCookie("username", user, 5);
}
}
}

Categories