Skip to content

Javascript redirect methods by geeksforgeeks

February 19, 2023 | 12:00 AM

Difference between

window.location.href, window.location.replace and window.location.assign in JavaScript

Window.location is a property that returns a Location object with information about the document’s current location. This Location object represents the location (URL) of the object it is linked to i.e. holds all the information about the current document location (host, href, port, protocol, etc.)

All three commands are used to redirect the page to another page/website but differ in terms of their impact on the browser history.

window.location.href Property:

Syntax:

window.location.href = "https://www.geeksforgeeks.org";

Example

<!DOCTYPE html>
<html>
  <body>
    <button onclick="getCurrentLocation()">Get URL</button>
    <button onclick="setCurrentLocation()">Change URL</button>

    <script>
      function getCurrentLocation() {
        // Get current location
        var loc = window.location.href;
        alert(loc);
      }
      function setCurrentLocation() {
        // Change current location
        var newloc = "https://www.geeksforgeeks.org/";
        window.location.href = newloc;
      }
    </script>
  </body>
</html>

can also be written as

// Less favoured
window.location = "https://www.geeksforgeeks.org";

// More favoured
window.location.href = "https://www.geeksforgeeks.org";

window.location.replace Property:

Syntax:

window.location.replace("https://geeksforgeeks.org/web-development/");

Example:

<!DOCTYPE html>
<html>
  <body>
    <button onclick="replaceLocation()">Replace current webpage</button>
    <script>
      function replaceLocation() {
        // Replace the current location
        // with new location
        var newloc = "https://www.geeksforgeeks.org/";
        window.location.replace(newloc);
      }
    </script>
  </body>
</html>

window.location.assign Property:

Syntax:

window.location.assign("https://geeksforgeeks.org/");

Example:

<!DOCTYPE html>
<html>
  <body>
    <button onclick="assignLocation()">Go to new webpage</button>

    <script>
      function assignLocation() {
        // Go to another webpage (geeksforgeeks)
        var newloc = "https://www.geeksforgeeks.org/";
        window.location.assign(newloc);
      }
    </script>
  </body>
</html>

source