Redirection JavaScript is nothing but redirecting the current pages to defined web pages. The objects used to redirect JavaScript pages are:
Navigator Object
Location Object
Browser Detection
Description
To detect the browser that is being used to access the internet, the Window Navigator Object is used.
The method window.navigator can be used without the prefix “window”. Do not use the navigator object to detect the browser version because the navigator data can be changed by the owner of the browser.
URL Redirection JavaScript is done using the window.location method. This is used in company websites to navigate between the pages.
Example
[html]
<!DOCTYPE html>
<html>
<head>
<script>
function newLocation()
{
window.location="http://www.splessons.com";
}
</script>
</head>
<body>
<input type="button" value="Go to new location" onclick="newLocation()">
</body>
</html>[/html]
Output:
When the button in the above image is clicked, the page redirects to splessons.com web page.
Screen Redirect
Description
Screen Redirection will be helpful when there is a variation of the web page usage in various devices. The web page has to adjust the changes made as per the screen.
Example
[html]
<html>
<head>
<script type="text/javascript">
document.write("The screen width is : ", screen.width);
if (screen.width >= 699) {
document.location = "http://splessons.com";
}
</script>
</head>
<body>
</body>
</html>[/html]
In the above example, if the screen width is greater than 699 pixels, the page directs to splessons.com site. The output will be as follows.
As the screen width is 1366 pixels, the page redirects to splessons.com as shown below.
Summary
Key Points
Navigator Object is used for Browser Detection.
In JavaScript, URL redirection is done using the window.location method.
For mobile users, screen redirection is done using location object