JavaScript - SPLessons

Redirection JavaScript

Home > Lesson > Chapter 25
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Redirection JavaScript

Redirection JavaScript

shape Description

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

shape 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.

shape Examples

[html] <!DOCTYPE html> <html> <head> </head> <body> <div id="test"></div> <script> txt = "<p>Browser Creator: " + navigator.appCodeName + "</p>"; txt = "<p>Browser Name: " + navigator.appName + "</p>"; txt = "<p>Browser version and Operating system: " + navigator.appVersion + "</p>"; txt = "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>"; document.getElementById("test").innerHTML=txt; </script> </body> </html>[/html]

URL Redirection

shape Description

URL Redirection JavaScript is done using the window.location method. This is used in company websites to navigate between the pages.

shape 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

shape 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.

shape 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

shape 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