Reputation: 1
I'm using a quick Javascript code (based on a tutorial) to try and create an age screen on a site. However, although the age screen should only pop up once and then be fine for a while, it pops up every refresh. Here's the code I'm using:
<script type="text/javascript">
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];
while(c.charAt(0)==' ') c = c.substring(1);
if(c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
function checkCookie() {
var age = getCookie("allowed");
if (age != true) {
age = confirm("you must be 18 or older to enter and view the content on this blog");
}
if (age == true) {
setCookie("allowed", age, 7);
} else if (age == false) {
//window.location.replace("http://tumblr.com/dashboard");
}
return age;
}
</script>
I've checked every available online resource and tutorial I can find, but nothing explains why this won't save the cookie properly. If I open the console, it recognizes the site creating the cookie, but gives me undefined values for everything.
If I have the console run the checkCookie() function, it returns the proper value depending on whether I clicked 'OK' or 'Cancel' but it still won't actually save that value into the cookie.
Can anyone think of any reason this might be happening?
UPDATE
After changing the age == true
checks from boolean checks into strings, it made no difference.
Upvotes: 0
Views: 1509
Reputation: 33618
The cookie is probably being saved. But your getCookie method has a typo in it on like 6 c.substring(name,length,c.length);
Instead you should have c.substring(name.length,c.length);
Change the following lines in your checkCookie method to
if (age) {
setCookie("allowed", age, 7);
}
OR
if (age === true) {
setCookie("allowed", age, 7);
}
Once the setCookie is called, refresh the browser and you should be able to see the cookie set.
getCookie
returns a string so it should be age != "true"
and
confirm
returns a boolean so age === true
should work
var age = getCookie("allowed");
if (age != "true") {
age = confirm("you must be 18 or older to enter and view the content on this blog");
}
if (age === true) {
setCookie("allowed", age, 7);
} else if (age == false) {
//window.location.replace("http://tumblr.com/dashboard");
}
Upvotes: 1
Reputation: 45632
(typeof age)
is string
so you can either change age != true
to age != 'true'
and the same for other checks or convert it to Boolean like !!age != true
Upvotes: 0