Home >Web Front-end >JS Tutorial >Tutorial on implementing page redirection function using JavaScript_Basic knowledge
What is page redirection?
When you click on a URL to visit a web page X, but internally you are directed to another page Y, simply because the page redirects. The concept is different from JavaScript page refresh .
There may be various reasons why you want to redirect from the original page. A few reasons listed below:
How does page redirection work?
Example 1:
This redirection of client-side pages using JavaScript is very simple. To redirect website visitors to a new page, just add a line in the head section as follows:
<head> <script type="text/javascript"> <!-- window.location="http://www.newlocation.com"; //--> </script> </head>
Example 2:
Can display corresponding information to website visitors before redirecting them to a new page. This will require a bit time delay to load the new page. Here is simple example to achieve the same:
<head> <script type="text/javascript"> <!-- function Redirect() { window.location="http://www.newlocation.com"; } document.write("You will be redirected to main page in 10 sec."); setTimeout('Redirect()', 10000); //--> </script> </head>
The setTimeout() here is a built-in JavaScript function that can be used to execute another function after a given time interval.
Example 3:
The following is an example of redirecting visitors to different pages based on their browser:
<head> <script type="text/javascript"> <!-- var browsername=navigator.appName; if( browsername == "Netscape" ) { window.location="http://www.location.com/ns.html"; } else if ( browsername =="Microsoft Internet Explorer") { window.location="http://www.location.com/ie.html"; } else { window.location="http://www.location.com/other.html"; } //--> </script> </head>