CIS 119 - Redirection
Objectives
- use JavaScript to redirect users to other pages
- use the referrer property of the document object
Notes and examples
- when redirecting links with the onclick event handler, make sure you
return false to prevent the default of going to the href value
- example - fast redirection
document.location = "page2.html";
- example - nicer redirection with JavaScript detection
<p><a href="js02n.html"
onClick="window.location='js02j.html';return false;">
Click to Enter</a></p>
- example - showing last modified date and URL
document.write('Last modified on ' + document.lastModified);
document.write(document.URL);
- example - displaying document URL
document.writeln(document.URL + '<br />');
document.writeln(document.location + '<br />');
document.writeln(document.location.href + '<br />');
Redirection and the referrer property
<html>
<!-- redirect1.html -->
<head>
<title>Demonstration of redirect</title>
</head>
<body>
<h3>Demonstration of redirect</h3>
<script type="text/javascript">
<!--
window.location = "destination.html";
// -->
</script>
<noscript>
<p>This page needs JavaScript</p>
</noscript>
</body>
</html>
<html>
<!-- redirect2.html -->
<head>
<title>Demonstration of redirect</title>
<script type="text/javascript">
<!--
window.location = "destination.html";
// -->
</script>
</head>
<body>
<h3>Demonstration of redirect</h3>
<noscript>
<p>This page needs JavaScript</p>
</noscript>
</body>
</html>
<html>
<!-- redirect3.html -->
<head>
<title>Demonstration of random redirect</title>
<script type="text/javascript">
<!--
var pages = new Array();
pages[0] = "page1.html";
pages[1] = "page2.html";
pages[2] = "page3.html";
function redirect() {
var pagenum = Math.floor(Math.random() * pages.length);
window.location = pages[pagenum];
}
// -->
</script>
</head>
<body>
<h3>Demonstration of random redirect</h3>
<p>Go to the <a href="destination.html" onclick="redirect();return false;">destination</a>.</p>
</body>
</html>
<html>
<!-- destination.html -->
<head>
<title>Destination for redirect pages</title>
<script type="text/javascript">
<!--
alert(document.referrer);
// -->
</script>
</head>
<body>
<h3>Destination for redirect pages</h3>
<p>You got here!</p>
<script>
<!--
if (document.referrer != "") {
document.writeln('<p><a href="' + document.referrer + '">Go back to ' + document.referrer + '</a></p>');
}
// -->
</script>
</body>
</html>