Ways To Redirect A Page In JavaScript

Introduction

In one of the articles, I described the multiple ways to refresh a page in Javascript. Similarly, I will explain the multiple ways to redirect a page in Javascript; we can use any of them in the project according to our requirements.

  • window.location.href
  • assign()
  • replace()
  • history.back()
  • history.forward()

window.location.href

The most common way to redirect an URL using JavaScript is just by setting the href attribute of the window.location object. It loads a page from the browser's cache and does not always send the request to the server.

window.location.href="https://www.c-sharpcorner.com"

So, if you have an old version of the page available in the cache, then it will redirect there instead of loading a fresh page from the server.

assign()

This function adds a new URL to the history stack and redirects to the new URL, Use the assign() method for redirection if you want to allow the user to use the back button to return to the original document. 

window.location.assign("https://www.c-sharpcorner.com/"); 

replace()

If you want to redirect to a new page and don't allow the user to navigate to the original page using the back button, This method removes the current URL from the history and replaces it with a new URL. Here is an example of how to use this function for redirection:

window.location.replace("https://www.c-sharpcorner.com/");

history.back()

This method loads the previous URL from the browser history list.

window.history.back(); 
window.history.go(-1);  
window.history.back(-1);

history.forward()

This method loads the next URL in the history list

window.history.forward()

Conclusion

So these are the multiple ways, and you can use any of the above as per your requirement to redirect the page. Also, let me know if you think there is any other way to redirect the page in javascript.

Happy Coding :)


Similar Articles