Page Redirect with JavaScript window.location

The Page redirection is a way to automatically redirect a web page to another web page. The redirect page is often on the same website, or it can be on a different website or a web server. In JavaScript the window.location object is used to redirect the browser to a new web page. The syntax is as follows :
  window.location = "URL of new location to redirect";
Example :
<html>
<body>
  <input type="button" onclick="MyFunc()" value="Click here to Redirect"/> 
  <script>
    function MyFunc() {
      window.location = "http://www.mycsnotes.com";
    }
  </script>
</body>
</html>
Output :


There are also other methods are available in window.location object. Which are as follows :

window.location.href : The window.location.href returns the URL of the current page.

Example :
<html>
<body>
  <input type="button" onclick="MyFunc()" value="Click here"/> 
  <p id="demo1"></p>
  <script>
    function MyFunc() {
      document.getElementById("demo1").innerText = window.location.href;
    }
  </script>
</body>
</html>
Output :



window.location.hostname : The window.location.hostname method returns the domain name of the host name.

Example :
<html>
<body>
  <input type="button" onclick="MyFunc()" value="Click here"/> 
  <p id="demo2"></p>
  <script>
    function MyFunc() {
      document.getElementById("demo2").innerText = window.location.hostname;
    }
  </script>
</body>
</html>
Output :



window.location.pathname : The window.location.pathname method returns the path and filename of the current page.

Example :
<html>
<body>
  <input type="button" onclick="MyFunc()" value="Click here"/> 
  <p id="demo3"></p>
  <script>
    function MyFunc() {
      document.getElementById("demo3").innerText = window.location.pathname;
    }
  </script>
</body>
</html>
Output :



window.location.protocol : The window.location.protocol method returns the web protocol use (http/https).

Example :
<html>
<body>
  <input type="button" onclick="MyFunc()" value="Click here"/> 
  <p id="demo4"></p>
  <script>
    function MyFunc() {
      document.getElementById("demo4").innerText = window.location.protocol;
    }
  </script>
</body>
</html>
Output :



window.location.assign : The window.location.assign method loads a new document.

Example :
<html>
<body>
  <input type="button" onclick="MyFunc()" value="Click here"/> 
  <script>
    function MyFunc() {
      window.location.assign("http://mycsnotes.com");
    }
  </script>
</body>
</html>
Output :


Next Topic :