How to set and read cookies JavaScript - javascript

I'm trying to make a popup that appears on my site the first time you visit it. But not any other time after that. So I'm trying to make it with cookies. But I'm having absolutely no luck.
I've tried following W3 school's tutorial but I haven't gotten anywhere.
What I'm doing is when the user closes the dialog, it sets a cookie. And I'm trying to make it so when you come back, the pop up doesn't appear because the cookie is set.
Here's my code.
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
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);
}
return "";
}
function checkCookie() {
var username=getCookie("username");
if (username!="") {
$('#firsttimee').css({display : 'none'});
} else {
if (username=="" || username==null) {
$('#firsttimee').css({display : 'block'});
}
}
}
function closepop(){
$('#firsttimee').css({display : 'none'});
var username = 'seen';
setCookie("username",username,365);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="firsttimee">
<div id="firsttimetxt">
<center>
Click here.<br><br>
Done
</center>
</div>
</div>
Thanks in advance! :)
Here is a jsfidddle of my current work, for some reason when you click done the popup doesn't go away..

Use the cookie script from MDN, not W3Schools, looks like W3Schools is not setting the path.
var docCookies = {
getItem: function (sKey) {
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!sKey || !this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: /* optional method: you can safely remove it! */ function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
and to set the cookie
docCookies.setItem("username",username,"Infinity");
and to get the cookie
docCookies.getItem("username") //returns the string
or
docCookies.has("username") //return boolean

I usually use below code for that:
function getCookie(cookieName) {
var i, x, y, cookiesArray = document.cookie.split(";");
for (i = 0; i < cookiesArray.length; i++) {
x = cookiesArray[i].substr(0, cookiesArray[i].indexOf("="));
y = cookiesArray[i].substr(cookiesArray[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == cookieName) {
return unescape(y);
}
}
}
function checkCookie() {
hideCookieDiv();
var myCookie = getCookie("yourcookiename");
if (myCookie == null || myCookie != "true") {
showCookieDiv();
setCookie();
}
}
function hideCookieDiv() {
document.getElementById('YourDivId').style.display = "none";
}
function showCookieDiv() {
document.getElementById('YourDivId').style.display = "block";
}
function setCookie() {
var expirationDate = new Date();
expirationDate.setDate(expirationDate.getDate() + 365);
document.cookie = "yourcookiename=true; expires=" + expirationDate.toUTCString();
}

Related

How to call a specific cookie is JS [duplicate]

This question already has answers here:
How do I create and read a value from cookie with javascript?
(23 answers)
Closed 8 years ago.
I'm trying to set a cookie depending on which CSS file I choose in my HTML. I have a form with a list of options, and different CSS files as values. When I choose a file, it should be saved to a cookie for about a week. The next time you open your HTML file, it should be the previous file you've chosen.
JavaScript code:
function cssLayout() {
document.getElementById("css").href = this.value;
}
function setCookie(){
var date = new Date("Februari 10, 2013");
var dateString = date.toGMTString();
var cookieString = "Css=document.getElementById("css").href" + dateString;
document.cookie = cookieString;
}
function getCookie(){
alert(document.cookie);
}
HTML code:
<form>
Select your css layout:<br>
<select id="myList">
<option value="style-1.css">CSS1</option>
<option value="style-2.css">CSS2</option>
<option value="style-3.css">CSS3</option>
<option value="style-4.css">CSS4</option>
</select>
</form>
I find the following code to be much simpler than anything else:
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=/";
}
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;
}
function eraseCookie(name) {
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
Now, calling functions
setCookie('ppkcookie','testcookie',7);
var x = getCookie('ppkcookie');
if (x) {
[do something with x]
}
Source - http://www.quirksmode.org/js/cookies.html
They updated the page today so everything in the page should be latest as of now.
These are much much better references than w3schools (the most awful web reference ever made):
How cookies work (quirksmode.org)
MDN document.cookie
Examples derived from these references:
// sets the cookie cookie1
document.cookie = 'cookie1=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'
// sets the cookie cookie2 (cookie1 is *not* overwritten)
document.cookie = 'cookie2=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'
// remove cookie2
document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'
The Mozilla reference even has a nice cookie library you can use.
Check JavaScript Cookies on W3Schools.com for setting and getting cookie values via JS.
Just use the setCookie and getCookie methods mentioned there.
So, the code will look something like:
<script>
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(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);
}
}
}
function cssSelected() {
var cssSelected = $('#myList')[0].value;
if (cssSelected !== "select") {
setCookie("selectedCSS", cssSelected, 3);
}
}
$(document).ready(function() {
$('#myList')[0].value = getCookie("selectedCSS");
})
</script>
<select id="myList" onchange="cssSelected();">
<option value="select">--Select--</option>
<option value="style-1.css">CSS1</option>
<option value="style-2.css">CSS2</option>
<option value="style-3.css">CSS3</option>
<option value="style-4.css">CSS4</option>
</select>
I'm sure this question should have a more general answer with some reusable code that works with cookies as key-value pairs.
This snippet is taken from MDN and probably is trustable. This is UTF-safe object for work with cookies:
var docCookies = {
getItem: function (sKey) {
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!sKey || !this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: /* optional method: you can safely remove it! */ function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
Mozilla has some tests to prove this works in all cases.
There is an alternative snippet here:

Cookie in html webview android

Hi I need to know is how to read cookies on a html web-view . I have a banner to close it generates a cookie and the idea would be to go to another page that has the banner he would read the cookie to see if the User already have clicked ...
this is the cookie code
function createCookie() {
var d = new Date();
d.setTime(d.getTime() + (1*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = "cookie=cookie ; " + expires+';path = http://www.pitstop.com.br/';
document.getElementById('banner_id').style.display='none';
}
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 banner_cookie(){
var teste = getCookie('cookie');
if(teste !=null){
alert(teste);
document.getElementById('banner_id').style.display='none';
}else{
document.getElementById('banner_id').style.display
}
}
You have many issues that seems to stem from wishful thinking and misunderstanding.
For example your path is wrong and you need to pass a name to the cookie script instead of hardcoding the name "cookie"
You need to take a well tested cookie script and use it properly.
function getCookie(name) {
var start = document.cookie.indexOf(name + "=");
var len = start + name.length + 1;
if ((!start) && (name != document.cookie.substring(0, name.length))) {
return null;
}
if (start == -1) return null;
var end = document.cookie.indexOf(';', len);
if (end == -1) end = document.cookie.length;
return unescape(document.cookie.substring(len, end));
}
function setCookie(name, value, expires, path, domain, secure) {
var today = new Date();
today.setTime(today.getTime());
if (expires) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date(today.getTime() + (expires));
document.cookie = name + '=' + escape(value) +
((expires) ? ';expires=' + expires_date.toGMTString() : '') + //expires.toGMTString()
((path) ? ';path=' + path : '') +
((domain) ? ';domain=' + domain : '') +
((secure) ? ';secure' : '');
}
function deleteCookie(name, path, domain) {
if (getCookie(name)) document.cookie = name + '=' +
((path) ? ';path=' + path : '') +
((domain) ? ';domain=' + domain : '') +
';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}
Your script:
function banner_cookie(){
var teste = getCookie('showbanner')=="true";
document.getElementById('banner_id').style.display=teste?"block":"none";
}
and to set:
setCookie("showbanner","true",14,"/"); // 2 weeks accessible to all website
and to remove
deleteCookie("showbanner","/");

Set cookie and get cookie with JavaScript [duplicate]

This question already has answers here:
How do I create and read a value from cookie with javascript?
(23 answers)
Closed 8 years ago.
I'm trying to set a cookie depending on which CSS file I choose in my HTML. I have a form with a list of options, and different CSS files as values. When I choose a file, it should be saved to a cookie for about a week. The next time you open your HTML file, it should be the previous file you've chosen.
JavaScript code:
function cssLayout() {
document.getElementById("css").href = this.value;
}
function setCookie(){
var date = new Date("Februari 10, 2013");
var dateString = date.toGMTString();
var cookieString = "Css=document.getElementById("css").href" + dateString;
document.cookie = cookieString;
}
function getCookie(){
alert(document.cookie);
}
HTML code:
<form>
Select your css layout:<br>
<select id="myList">
<option value="style-1.css">CSS1</option>
<option value="style-2.css">CSS2</option>
<option value="style-3.css">CSS3</option>
<option value="style-4.css">CSS4</option>
</select>
</form>
I find the following code to be much simpler than anything else:
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=/";
}
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;
}
function eraseCookie(name) {
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
Now, calling functions
setCookie('ppkcookie','testcookie',7);
var x = getCookie('ppkcookie');
if (x) {
[do something with x]
}
Source - http://www.quirksmode.org/js/cookies.html
They updated the page today so everything in the page should be latest as of now.
These are much much better references than w3schools (the most awful web reference ever made):
How cookies work (quirksmode.org)
MDN document.cookie
Examples derived from these references:
// sets the cookie cookie1
document.cookie = 'cookie1=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'
// sets the cookie cookie2 (cookie1 is *not* overwritten)
document.cookie = 'cookie2=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'
// remove cookie2
document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'
The Mozilla reference even has a nice cookie library you can use.
Check JavaScript Cookies on W3Schools.com for setting and getting cookie values via JS.
Just use the setCookie and getCookie methods mentioned there.
So, the code will look something like:
<script>
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(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);
}
}
}
function cssSelected() {
var cssSelected = $('#myList')[0].value;
if (cssSelected !== "select") {
setCookie("selectedCSS", cssSelected, 3);
}
}
$(document).ready(function() {
$('#myList')[0].value = getCookie("selectedCSS");
})
</script>
<select id="myList" onchange="cssSelected();">
<option value="select">--Select--</option>
<option value="style-1.css">CSS1</option>
<option value="style-2.css">CSS2</option>
<option value="style-3.css">CSS3</option>
<option value="style-4.css">CSS4</option>
</select>
I'm sure this question should have a more general answer with some reusable code that works with cookies as key-value pairs.
This snippet is taken from MDN and probably is trustable. This is UTF-safe object for work with cookies:
var docCookies = {
getItem: function (sKey) {
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!sKey || !this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: /* optional method: you can safely remove it! */ function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
Mozilla has some tests to prove this works in all cases.
There is an alternative snippet here:

Javascript: Reading a cookie

I am seeing lots and lots of functions for reading cookies in via java script, but I only want to use it once and inside a variable, I am new to JS.
Here is my code
var TheNumber = (Math.random() + '') * 1000000000000000000;
document.cookie= "rand=" + TheNumber.toString() + ";path=/";
var AdServer = {
tile: 1,
mock: false,
ord: (Math.random() + "") * 1000000000000000000 + '?',
I want to replace the ord part with the value from the rand cookie.
Could you guide me on the following:
Do I need a function?
If so where do I put it?
How would I call it?
I find the easiest (and most flexible) way to write/read from cookies with JavaScript is with global object with getter/setter methods.
The Mozilla dev docs page on document.cookie has a well documented example: https://developer.mozilla.org/en/DOM/document.cookie
How/where you might instantiate and then reference that object depends on the rest of your program, but assuming for simplicity we're just in the global namespace and aren't worried about variable collision etc:
var docCookies = {
getItem: function (sKey) {
if (!sKey || !this.hasItem(sKey)) { return null; }
return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/.test(sKey)) { return; }
var sExpires = "";
if (vEnd) {
switch (typeof vEnd) {
case "number": sExpires = "; max-age=" + vEnd; break;
case "string": sExpires = "; expires=" + vEnd; break;
case "object": if (vEnd.hasOwnProperty("toGMTString")) { sExpires = "; expires=" + vEnd.toGMTString(); } break;
}
}
document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
},
hasItem: function (sKey) { return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); }
}
Then set your cookie with:
docCookies.setItem('rand', (Math.random()* 1000000000000000000).toString());
And get it with:
docCookies.getItem('rand');
So to put it all together:
var docCookies = {
getItem: function (sKey) {
if (!sKey || !this.hasItem(sKey)) { return null; }
return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/.test(sKey)) { return; }
var sExpires = "";
if (vEnd) {
switch (typeof vEnd) {
case "number": sExpires = "; max-age=" + vEnd; break;
case "string": sExpires = "; expires=" + vEnd; break;
case "object": if (vEnd.hasOwnProperty("toGMTString")) { sExpires = "; expires=" + vEnd.toGMTString(); } break;
}
}
document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
},
hasItem: function (sKey) { return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); }
}
//set our cookie
docCookies.setItem('rand', (Math.random()* 1000000000000000000).toString());
then later/elsewhere in your code when you want to retrieve the cookie value:
var AdServer = {
tile: 1,
mock: false,
ord: docCookies.getItem('rand')
};
Now if you inspect AdSever.ord it will equal the random number from your rand cookie that you set earlier.
console.log(AdServer.ord);

How to update and delete a cookie?

I need help to know how to update values and how to delete a cookie created from this code! I'm new to JavaScript so it's great if anyone can help me.
function getCookie(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);
}
}
}
function setCookie(c_name,value,exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function check2Cookie() {
var username=getCookie("username");
if (username!=null && username!="") {
username= "0";
setCookie("username",username,1000);
}
else {
username=" ";
if (username!=null && username!="") {
username= "0";
setCookie("username",username,1000);
}
}
}
This is the code for cookie creation.
Code for creating is setCookie("username",username,1000);
Now how to update this cookie and delete this cookie.
The cookie API is kind of lame. Let me clarify...
You don't update cookies; you overwrite them:
document.cookie = "username=Arnold"; // Create 'username' cookie
document.cookie = "username=Chuck"; // Update, i.e. overwrite, the 'username' cookie to "Chuck"
You also don't delete cookies; you expire them by setting the expires key to a time in the past (-1 works too).
Source: https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
http://www.quirksmode.org/js/cookies.html
update would just be resetting it using createCookie
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);
}
http://www.quirksmode.org/js/cookies.html
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);
}
check this out A little framework: a complete cookies reader/writer with full Unicode support
/*\
|*|
|*| :: cookies.js ::
|*|
|*| A complete cookies reader/writer framework with full unicode support.
|*|
|*| Revision #1 - September 4, 2014
|*|
|*| https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*| https://developer.mozilla.org/User:fusionchess
|*| https://github.com/madmurphy/cookies.js
|*|
|*| This framework is released under the GNU Public License, version 3 or later.
|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*| Syntaxes:
|*|
|*| * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*| * docCookies.getItem(name)
|*| * docCookies.removeItem(name[, path[, domain]])
|*| * docCookies.hasItem(name)
|*| * docCookies.keys()
|*|
\*/
var docCookies = {
getItem: function (sKey) {
if (!sKey) { return null; }
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
if (!sKey) { return false; }
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};

Categories