Javascript - Using cookies to store an integer - javascript

I am trying to use a cookie to store a single integer, so when the user refreshes the page I am able to retrieve the previous number they were on (in an attempt to stop doubles of a video appearing).
What would the minimum requirements be to accomplish this?
var randomNumber = Math.floor((Math.random()*10)+1);
document.cookie=(randomNumber);
Setting a cookie:
document.cookie = 'mycookie=' + randomNumber + ";max-age=" + (300) + ";";
Reading a cookie:
var cookie = document.cookie;
alert(decodeURIComponent(cookie));
The cookie contains some other random stuff like push=1 as well as mycookie. Should I be setting the cookie to null before I add the randomNumber?
As far as getting the value of mycookie would I just assign the cookie to a string and parse mycookie from it?

Tamil's comment is solid. Use these quirksmode functions if you ever wish to surpass minimal cookie usage:
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;
};

You could use document.cookie to read/write cookies in javascript:
document.cookie = 'mycookie=' + randomNumber + '; path=/';
And if you wanted the cookie to be persistent even after the user closing his browser you could specify an expires date.

Related

Javascript - Popup every time customer enters the store

I saw the age-verification snippet solution for my problem and it worked great. But in that solution the occurrence of that popup is based on the number of days. I want the popup to occur every time the user enters my website. How to do it?
Here's is the JS part of the snippet code.
<script>
function ageCheck() {
var min_age = {{ age }}; // Set the minimum age.
var year = parseInt(document.getElementById('byear').value);
var month = parseInt(document.getElementById('bmonth').value);
var day = parseInt(document.getElementById('bday').value);
var theirDate = new Date((year + min_age), month, day);
var today = new Date;
if ((today.getTime() - theirDate.getTime()) < 0) {
window.location = 'http://google.com'; //enter domain url where you would like the underaged visitor to be sent to.
} else {
var days = 1; //number of days until they must go through the age checker again.
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
document.cookie = 'isAnAdult=true;'+expires+"; path=/";
location.reload();
};
};
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;
};
var isAnAdult = readCookie('isAnAdult');
if (isAnAdult) {
document.write("<style> #prompt-background { display: none; }</style>");
};
</script>
and the button that function is called on
<button id="submit_birthdate" class="exitbutton" onclick="ageCheck()">Enter</button>
How to modify this code so that the popup appears every time?

Implementing own Client ID shows discrepancies compared to GA Client ID

I want to implement my own Test-Client ID with the following Skript:
<script>
(function(){
var cookie = readCookie("customClientID");
var storage = window.localStorage;
var storageClientID = storage.getItem("customClientID"");
var userID = userId();
var agent = window.navigator.userAgent;
if(!cookie && !storageClientID){
createCookie("customClientID"", userID, 2);
storage.setItem("customClientID"", readCookie("customClientID""));
}else if(cookie && !storageClientID){
storage.setItem("customClientID"", readCookie("customClientID""));
}else if(!cookie && storageClientID){
createCookie("customClientID"", storageUserId, 2);
}else{}
//Create UUID
function userId() {
try{
return new Date().getTime() + '.' + Math.random().toString(36).substring(5) + '.' + hash(agent);
}catch(e){}
}
//Hash Function
function hash(str){
try{
var hash = 0;
for(var i = 0; i < str.length; i++){
var charI = str.charCodeAt(i);
hash = ((hash<<5)-hash)+charI;
hash = hash & hash; // Convert to 32bit integer
}
hash = hash & hash;
hash = hash.toString().replace("-", "");
return hash;
}catch(e){}
}
//Read Cookie https://www.quirksmode.org/
function readCookie(name) {
try{
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;
}catch(e){}
}
//Create Cookie https://www.quirksmode.org/
function createCookie(name,value,days) {
try{
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}catch(e){}
}
})();
The if block checks if the cookie is set and the cookie value also appears in the local storage. If the cookie is not found a new cookie is set with a value generated function userId().
To get the customClientID value out of the cookie I use the internal GTM First Party Cookie variable. The custom HTML tag with the script above fires on All Pages - Pageview.
Finally I've set a Custom Dimension (User Scope) with the First Party Cookie variable (customClientID) value in each tag.
When I compare the Users Metric of the original GA ClientID I get 1 User for each ClientID which is correct. However, if I compare the customClientID in a custom report with the same date range e.g. one day I get a lot of Users with the same customClientID. There are also less Users in sum compared to the original ClientID.
We have a high traffic website so my first assumption is that the script is maybe to slow to handle a lot of users entering and browsing at the same time. Many users would get the same customClientID.
Second assumption is that the custom dimension should only set within the page view tag.
Hope you understand my issue and many thanks in advance!
PS: I posted it here https://productforums.google.com/forum/#!topic/tag-manager/syet129zIqI;context-place=forum/tag-manager as well.
Best,
Anton

set cookie on page to show bootstrap popup once a day

I'm learning JavaScript and I see that this question has been asked many times, but I can't get this to work for me.
What I want to do is, show a bootstrap modal once a day.
What I have so far is:
function setCookie(cookiename, cookievalue, expdays) {
var d = new Date();
d.setTime(d.getTime()+(expdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cookiename + "=" + cookievalue + "; " + expires;
}
function getCookie(cookiename) {
var name = cookiename + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
//I want to check if there is a cookie.
//if I have not set a cookie, I want to show my modal,
//if there is a cookie then return;
//The cookie should expire in one day.
function checkCookie() {
var showed = getCookie("showed");
if (showed != null && showed != "") {
var date = new Date(showed).getDate();
var currentDate = new Date().getDate();
if (currentDate > date) {
return true;
}
return false;
}
return true;
}
Now, if I change the last return true; to return false; my modal does not show up.
The way it is now I see the modal every time.
What am I doing wrong?
How can I fix this?
function setCookie(cookiename, cookievalue, expdays) {
var d = new Date();
d.setTime(d.getTime()+(expdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cookiename + "=" + cookievalue + "; " + expires;
}
function getCookie(cookiename) {
var name = cookiename + "=";
var startPos = document.cookie.indexOf(name);
if(startPos == -1) return null;
startPos+=(name.length);
if(document.cookie.indexOf(";",startPos) == -1){
return document.cookie.substring(startPos,document.cookie.length);
}
else{
return document.cookie.substring(startPos,document.cookie.indexOf(';',startPos));
}
return null;
}
//I want to check if there is a cookie.
//if I have not set a cookie, I want to show my modal,
//if there is a cookie then return;
//The cookie should expire in one day.
function checkCookie() {
var showed = getCookie("showed");
if (showed != null && showed != "") {
var date = new Date(showed).getDate();
var currentDate = new Date().getDate();
if (currentDate > date) {
return true;
}
return false;
}
return true;
}
Also when setting cookie,
use
setCookie('showed',new Date().toGMTString(),1);
because we are using the value of cookie, not the expire time of cookie to check. So the value must be a datestring

Clear all cookie using Javascript

Is there anyway to clear the cookie using javascript?
First, I need to clearify the problem. Many posts in StackOverflow give this kind of answer. But it is clearing cookie like setting the value of all the keys to empty string. But I need to erase the keys as well. How can I do that?
PS: I tried document.cookie = null, but it does not work here
The best way I found is to expire the cookie you want to delete, use this javascript:
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
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;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}

Cookie value to define style on page load

I am using the scripts from here http://www.quirksmode.org/js/cookies.html and have successfully created a cookie.. it is set based on the users response to the age drop down. However I am having trouble doing anything with it. I would like to have a style defined if a cookie is present. Here is the bulk of my scripts..
function createCookie(name,value,days){
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
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;
}
function checkAge(){
var min_age = 13;
var year = parseInt(document.forms["emailForm"]["year"].value);
var month = parseInt(document.forms["emailForm"]["month"].value) - 1;
var day = parseInt(document.forms["emailForm"]["day"].value);
var theirDate = new Date((year + min_age), month, day);
var today = new Date;
if ( (today.getTime() - theirDate.getTime()) < 0) {
var el = document.getElementById('emailBox');
if(el){
el.className += el.className ? ' youngOne' : 'youngOne';
}
document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>";
createCookie('age','not13',0)
return false;
}
else {
createCookie('age','over13',0)
return true;
};
};
window.onload=function(){
var x = readCookie('not13');
if (x) {
document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>";
}
}
Age verification works and cookie is set.... no errors (from Firebug).. can anyone see what I am doing wrong?
with jQuery would be something like this
if (x) {
var style = "<style type=\"text/css\">.form {display:none}</style>";
$("header").append(style);
}
Looking at your code it should work. There's nothing incorrect about it.
The only thing I would suggest is that instead of injecting a style tag into a empty div, inject a link tag into the head. This will mean that your css changes and maintainance won't need to touch the js code.
I got it.. I was looking for the cookie value and needed to look for the name and then create an if statement based on the value. so..
var x = readCookie('age');
if (x=='not13') {
document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>";
}

Categories

Resources