How to redirect to another webpage using JavaScript?

CodingTute

FAQ
FAQ

In this article, you will learn how to redirect to another webpage using JavaScript in multiple ways.

To redirect to another webpage using JavaScript, we can make use of the window.location object which represents the current URL or location of the browser window. There are several methods to set this location to a new URL, but the three most commonly used methods are:

Redirection using the href

To redirect to another webpage using JavaScript, you can use the window.location.href property.

Here’s an example:

window.location.href = "https://www.example.com";

This will redirect the current webpage to the URL mentioned in the href property.

Using the assign method

The assign() method sets the URL property of the Location object to a new value. This method has the effect of loading the new URL in the same frame or window as the calling page.

Example code:

window.location.assign("http://www.example.com");

This will redirect the browser to the webpage specified in the parameter, i.e., http://www.example.com.

Using the replace method

The replace() method is similar to the assign() method, but it differs in that it replaces the current history entry instead of creating a new one. This means that when you use the back button in the browser, you will jump back to the page before the one that used replace().

Example code:

window.location.replace("http://www.example.com");

This will redirect the browser to the webpage specified in the parameter, i.e., http://www.example.com, and eliminate the current page from the browsing history.

Conclusion

In conclusion, we have seen how to redirect to another webpage using two different methods in JavaScript. The assign() method navigates to a new URL and creates a new entry in the browsing history, while the replace() method navigates to a new URL and replaces the current entry in the browsing history. It’s important to note that you should only use these methods where necessary and with caution, as they may affect the user experience and browser performance.

You can find the complete JavaScript Tutorials here.

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.

Leave a Comment