How to redirect to another webpage in Javascript?
Javascript | redirect | assign | replace | how to
Graduated with a Master’s degree in Software Engineering from San Jose State University in December 2019 and currently working at PayPal on the Customer Journey Platform. I enjoy generating new ideas and devising feasible solutions to broadly relevant problems. My colleagues would describe me as a driven, resourceful individual who maintains a positive, proactive attitude when faced with adversity. Interested to work in areas related to Distributed Systems, Cloud Infrastructure and Micro-Services. I get a lot of satisfaction from the constant learning and puzzle solving that comes with my profession and contributing to a successful and worthwhile product. My expertise includes project design and management, data analysis and interpretation, and the development and implementation of software products.
window.location.replace("<URL>") will best simulate an HTTP redirect.
window.location.replace("<URL>"): Replace method, will replace the current page with the one provided in the input parameter. The current page will not be saved in the session, so you won't be able to go back in history using 'Back' button in the browser.window.location.assign("<URL>"): Assign method, will redirect to the given URL but it will keep in history original document, so you can navigate to the previous website using 'Back' button.window.location.href = "<URL>": Using location.href to redirect to the different document will also keep the browser history just like the assign method.
Which one to use?
If you want to simulate someone clicking on a link, use
location.hrefIf you want to simulate an HTTP redirect, use
location.replace
For example:
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";