|
I get asked constantly for little snippets of code.
Instead of answering everyone one at a time I am starting a small PDF
library at
Stmadeveloper.com.
REDIRECTION USING JAVASCRIPT!
Download sample
files at Stmadeveloper Code Samples
I get asked constantly for little snippets of code. Instead of
answering everyone one at a time I am starting a small PDF library at
Stmadeveloper.com.
1. Create cookieslib.js file with the following content:
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);
}
2. Below is the code of the first page (you should take into account
JS code only):
<html>
<head>
<!-- include JS code for cookies management from the cookielib.js file -->
<script type="text/javascript" language="javascript" src="cookielib.js">
</script>
<script type="text/javascript" language="javascript">
// set cookie
createCookie("cookiename", "test_value", 99999);
</script>
</head>
<body>
<a href="2.html">open 2.html</a>
</body>
</html>
3. Sample of a page which checks for cookie availability and redirects
an user to "url" if the cookie is set:
<html>
<head>
<script type="text/javascript" language="javascript" src="cookielib.js">
</script>
<script type="text/javascript" language="javascript">
// you may use any URL, just replace
http://google.com with yours
var url = "http://google.com";
if (readCookie('cookiename') != null) {
alert("you have cookie with cookiename; you are being
redirected to " + url);
document.location = url;
}
</script>
</head>
<body>
if you see this code, it means that your browser does not have
cookie "cookiename".
</body>
</html>
In order to remove the popup
window prior to redirection, just replace
alert("you have cookie with cookiename; you are being redirected to " +
url);
with
// alert("you have cookie with cookiename; you are being redirected to " +
url);
|