Site icon Puneet Sharma – Freelance Web Developer

Webpage redirect using JavaScript

Webpage redirect using JavaScript

Webpage redirects are the simplest but widely used functions in website development. Here are simple one-liner scripts that you can use on your web page if you want it to automatically redirect to another location or web page using JavaScript.

The two ways to do it is via location.href and location.replace:


window.location.href method

This method simulate a mouse click. The redirecting URL can be found in the history.

window.location.href = "https://webdevpuneet.com/javascript-redirect/";

Demo Link – https://demos.webdevpuneet.com/javascript/redirect/href.html

Demo Source

<button onclick="redirect()">Redirect to https://webdevpuneet.com/javascript-redirect/</button>

<script>
  function redirect() {
    window.location.href="https://webdevpuneet.com/javascript-redirect/";
  }
</script>

window.location.replace method

This method simulates an HTTP redirect. This removes the URL of the current document from the document history. You can use this method if you do not want the user to know the redirecting page like a permanent page redirect.

window.location.replace("https://webdevpuneet.com/javascript-redirect/");

Demo Link – https://demos.webdevpuneet.com/javascript/redirect/replace.html

Demo Source

<button onclick="redirect()">Redirect to https://webdevpuneet.com/javascript-redirect/</button>

<script>
  function redirect() {
    window.location.replace("https://webdevpuneet.com/javascript-redirect/")
  }
</script>

Redirection is quick if added in the <head> section of the document before any other JavaScript.

Questions that have the same solution:

Exit mobile version