...

View Full Version : Redirect when cookie NOT present?



monkeyboy
01-20-2006, 07:39 PM
Hello there. I'm very new to javascript and was hoping somebody could help me.

I've found a script that forwards you to a new page if you have stored a cookie on a previous visit... and am trying to make it do the opposite!

What I'm trying to achieve is a script that will leave the user on the page if they HAVE the cookie, but will forward them somewhere else if they DO NOT have it (ie in order to prevent people without the cookie from staying on the page).

The script I'm using is here:



<script>
<!--
/* Copyright http://www.perlscriptsjavascripts.com
Free and commercial Perl and JavaScripts */

// page to go to if cookie exists
go_to = "enter.htm";

function readCookie(cookieName){
var start = document.cookie.indexOf(cookieName);
if (start == -1){
document.cookie = "access=no; expires=" + ged(num_days);
} else {
window.location = go_to;
}
}

readCookie("access");
// -->
</script>


I don't particularly want people to have to log in to access the page - one password for everyone should suffice... is this possible? Am I making things unnnecessarily complicated?

All suggestions welcomed!

:)

Mr J
01-20-2006, 08:07 PM
You could swap your statements round maybe


<script>
<!--
/* Copyright http://www.perlscriptsjavascripts.com
Free and commercial Perl and JavaScripts */

// page to go to if cookie does not exist
go_to = "enter.htm";

function readCookie(cookieName){
var start = document.cookie.indexOf(cookieName);

if (start == -1){
window.location = go_to;
}
else{
document.cookie = "access=no; expires=" + ged(num_days);
}
}

readCookie("access");
// -->
</script>

Lerura
01-20-2006, 08:16 PM
or invert the test:
function readCookie(cookieName){
var start = document.cookie.indexOf(cookieName);
if (start != -1){
document.cookie = "access=no; expires=" + ged(num_days);
} else {
window.location = go_to;
}
}


!= means "is not"

monkeyboy
01-21-2006, 01:18 AM
That's brilliant, thanks!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum