How to usewindow.location.assign Property in Javascript

  • The assign function is similar to the href property as it is also used to navigate to a new URL.
  • The assign method, however, does not show the current location, it is only used to go to a new location.
  • Unlike the replace method, the assign method adds a new record to history (so that when the user clicks the “Back” button, he/she can return to the current page).

Syntax:

window.location.assign("https://w3wiki.org/")

Example: This example shows the use of the window.location.assign property.

HTML




<!DOCTYPE html>
<html>
<body>
    <button onclick="assignLocation()">
        Go to new webpage
    </button>
     
    <script>
        function assignLocation() {
 
            // Go to another webpage (w3wiki)
            let newloc = "https://www.w3wiki.org/";
            window.location.assign(newloc);
        }
    </script>
</body>
</html>


Output:



How can a page be forced to load another page in JavaScript ?

In JavaScript, you can force a page to load another page by using the window.location object. There are a few methods to achieve this. To force a page to load another page in JavaScript, we have multiple approaches:

Below are the approaches used to force a page to load another page in JavaScript:

Table of Content

  • Using window.location.replace
  • Using window.location.assign Property

Similar Reads

Approach 1: Using window.location.replace

The replace function is used to navigate to a new URL without adding a new record to the history....

Approach 2: Using window.location.assign Property

...