cookie_name = "Counter_Cookie";
function doCookie() {
if(document.cookie) {
index = document.cookie.indexOf(cookie_name);
}
else {
index = -1;
alert("Welcome the site! Please don't forget to bookmark this page!");
}
var expires = new Date();
expires.setFullYear(expires.getFullYear() + 1);
if (index == -1) {
document.cookie = cookie_name + "=1; expires=" + expires.toUTCString();
}
else {
countbegin = (document.cookie.indexOf("=", index) + 1);
countend = document.cookie.indexOf(";", index);
if (countend == -1) {
countend = document.cookie.length;
}
count = eval(document.cookie.substring(countbegin, countend)) + 1;
document.cookie=cookie_name+"="+count+"; expires=" + expires.toUTCString();
}
document.write("<p>You have been to my site "+getTimes()+".</p>");
}
function getTimes() {
if(document.cookie) {
index = document.cookie.indexOf(cookie_name);
if (index != -1) {
countbegin = (document.cookie.indexOf("=", index) + 1);
countend = document.cookie.indexOf(";", index);
if (countend == -1) {
countend = document.cookie.length;
}
count = document.cookie.substring(countbegin, countend);
if (count == 1) {
return (count+" time");
}
else {
return (count+" times");
}
}
}
return ("0 times");
}
I want to know how to get the last cookies expiration date to show the last time the person visited the site. I'm assuming I'll need an array but, I can't seem to find out how to do that with the code I've written.
The Microsoft says: "The browser is responsible for managing cookies, and the cookie's expiration time and date help the browser manage its store of cookies. Therefore, although you can read the name and value of a cookie, you cannot read the cookie's expiration date and time. When the browser sends cookie information to the server, the browser does not include the expiration information." http://msdn.microsoft.com/en-us/library/ms178194(v=vs.100).aspx
So you can append expire timestamp with separator into cookie's value: count + '|' + expires.getTime()
Then parse time in getTimes():
data = document.cookie.substring(countbegin, countend).split('|');
count = data[0];
expirationDate = new Date();
expirationDate.setTime(data[1]);
Whole code:
cookie_name = "Counter_Cookie";
function doCookie() {
if(document.cookie) {
index = document.cookie.indexOf(cookie_name);
}
else {
index = -1;
alert("Welcome the site! Please don't forget to bookmark this page!");
}
var expires = new Date();
expires.setFullYear(expires.getFullYear() + 1);
if (index == -1) {
document.cookie = cookie_name + "=1|" + expires.getTime() + "; expires=" + expires.toUTCString();
}
else {
countbegin = (document.cookie.indexOf("=", index) + 1);
countend = document.cookie.indexOf(";", index);
if (countend == -1) {
countend = document.cookie.length;
}
count = eval(document.cookie.substring(countbegin, countend)) + 1;
document.cookie=cookie_name+"="+count+"|" + expires.getTime() + "; expires=" + expires.toUTCString();
}
document.write("<p>You have been to my site "+getTimes()+".</p>");
}
function getTimes() {
if(document.cookie) {
index = document.cookie.indexOf(cookie_name);
if (index != -1) {
countbegin = (document.cookie.indexOf("=", index) + 1);
countend = document.cookie.indexOf(";", index);
if (countend == -1) {
countend = document.cookie.length;
}
data = document.cookie.substring(countbegin, countend).split('|');
count = data[0];
date = new Date();
date.setTime(data[1]);
if (count == 1) {
message = count+" time";
}
else {
message = count+" times";
}
return message + ", last expire: " + date.toUTCString();
}
}
return ("0 times");
}
Related
I have a problem. I need set cookie, when in the URL is "pecan", and text will be "do 30min". If in URL isn't "pecan" or cookie expire text will be "nad 30 min".
Cookie expire in 30min (this is 1/48).
I have this code:
<script type="text/javascript">
if(window.location.href.indexOf('pecan') != -1)
{
Cookies.set('ent_afil', 'one', { expires: 1/48 });
}
if (Cookies.get('ent_afil') == 'one')
{
document.write('do 30min');
}
else {
document.write('nad 30min');
}
</script>
But still no function.
Where is mistake?
Thank you.
Pavel
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
if(window.location.href.indexOf('pecan') != -1)
{
var now = new Date();
var minutes = 30;
now.setTime(now.getTime() + (minutes * 60 * 1000));
cookievalue ='one'+ ";"
document.cookie="ent_afil=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
<!--document.write ("Setting Cookies : " + "name=" + document.cookie );-->
}
var value=getCookie('ent_afil')
if(value == 'one')
{
document.write('do 30min');
}
else {
document.write('nad 30min');
}
When a user click on a button it would take them to a link but before they go to that link, the cookie will need to be set to either English (EN) or French (FR). I got an example here:
http://www.quirksmode.org/js/cookies.html
but for some reason, it's not reading in the cookie and I'm not sure where I'm going wrong.
This is what I have:
<!DOCTYPE html>
<html>
<body>
<p>This is for the Browser Cookies.</p>
<button onclick="EN_Cookie()">English Link</button> <button onclick="FR_Cookie()">French Link</button>
<script>
function EN_Cookie() {
setCookie("SMDCookie","EN",7);
//location.href = 'https://google.com';
}
function FR_Cookie() {
setCookie("SMDCookie","FR",7);
//location.href = 'https://google.com';
}
function setCookie(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=/";
}
</script>
</body>
</html>
Any suggestions??
I reviewed your code and found your set cookie function is correct.
May be your getCookie not working, i am sharing get cookie function:
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 "";
}
Here are functions you can use for creating and retrieving cookies
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
Copied from How do I create and read a value from cookie with javascript?
UPDATE - made with suggestions from below:
I have the following script that pops up a window, after 3 visits, and to only 20% of visitors. The expiration date is set and shows in Developer tools for expiring in 180 days, but it's still popping up. What am I doing wrong? Any help is appreciated, I do not know javascript at all very well. This has to be done all in plain javascript - no jQuery
//setting the expiration date to 6 months from now//
expDate = new Date;
// in the following line, 180 means 180 days.//
expDate.setTime(expDate.getTime() + 180 * 24 * 60 * 60 * 1000);
expDate.toGMTString();
//making the cookie//
function setCookie(name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=/wmb" + path : "") +
((domain) ? "; domain=www.example.com" + domain : "") +
((secure) ? "; secure" : "");
}
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 += 1;
}
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
return unescape(dc.substring(begin + prefix.length, end));
}
//cookie name is called CustomSurvey//
visits = getCookie('CustomSurvey');
if (!visits) {
visits = 1
};
if (visits < 4)
//Math.random is set so that 20% of those visits actually get the popup//
if ((Math.random() * (100 - 1) + 1) < 20) {
//get location of where this popup came from; also contains variable from SM that will trickle down into reporting to tell where it came from//
var currentLocation = window.location;
window.open("https:mysurvey.com" + "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400");
}
if (visits < 3) {
++visits;
cookieData = visits;
setCookie('CustomSurvey', cookieData, expDate)
}
I changed to what you suggested (except the url - that part is just made up (the real one pops up). I did everything suggested except when I changed the visits > 3 , now nothing pops up (after clearing cache and clicking about 50 times.
This is what I have now:
//setting the expiration date to 6 months from now//
expDate = new Date;
// in the following line, 180 means 180 days.//
expDate.setDate(expDate.getDate() + 180)
//making the cookie//
function setCookie(name, value, expires, path, domain, secure){
document.cookie= name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=/wmb" + path : "") +
((domain) ? "; domain=ptoweb.uspto.gov" + domain : "") +
((secure) ? "; secure" : "");
}
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 += 1;
}
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
return unescape(dc.substring(begin + prefix.length, end));
}
//cookie name is called CustomSurvey//
visits = getCookie('CustomSurvey');
if (!visits) {
visits = 1
};
if (visits > 3)
//Math.random is set so that 20% of those visits actually get the popup//
if ((Math.random() * (100 - 1) + 1) < 20) {
//get location of where this popup came from; also contains variable from SM that will trickle down into reporting to tell where it came from//
var currentLocation = window.location;
window.open("https://www.surveymonkey" + "?" + currentLocation, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400");
}
if (visits < 3) {
++visits;
cookieData = visits;
setCookie('CustomSurvey', cookieData, expDate)
}
function showhide() {
if( document.getElementById("hidethis").style.display=='none' ){
document.getElementById("hidethis").style.display = 'table-row'; // set to table-row instead of an empty string
}else{
document.getElementById("hidethis").style.display = 'none';
}
}
I have this working javascript function to hide a row in a table - like this
<tr id="hidethis" style="display:table-row;">
It works fine but i want to use cookies to remember which option user chose. I cant figure out how to properly set cookies, some advice would be much appreciated.
Try this:
You need to store the value in cookies and read those values on DOMContentLoaded event ad set your style accordingly
Reference used to create and read cookies values
var createCookie = function(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
};
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
document.addEventListener('DOMContentLoaded', function() {
var cookieVal = getCookie('display');
if (cookieVal) {
document.getElementById("hidethis").style.display = cookieVal;
}
});
function showhide() {
if (document.getElementById("hidethis").style.display == 'none') {
document.getElementById("hidethis").style.display = 'table-row'; // set to table-row instead of an empty string
createCookie('display', 'table-row', 365);
} else {
document.getElementById("hidethis").style.display = 'none';
createCookie('display', 'none', 365);
}
}
<table>
<tr id="hidethis" style="display:table-row;">
</table>
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);