How to Redirect a Page to a New Location Using JavaScript

It is possible to redirect a user to a new URL in several ways using JavaScript. This can be helpful in a situation when a user should be taken to a new page in your JavaScript program. Rather than sending a request server-side, it may be more efficient to redirect the user front-end.

 

JavaScript has access to the window.location object of the browsers History API. This means we can modify the location.pathname or simulate an href action in order to tell the browser to navigate to a new destination. location has many methods that will perform this exact same task so we will look at those in this tutorial.

 

Simulate an HTTP Redirect

One of the most common ways to redirect to a new webpage in JavaScript is by using the replace method on the location object to simulate an HTTP redirect.

 

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

 

Simulate a Mouse Click

Another way is to simulate a mouse click with the href property on the location object.

 

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

 

Redirect to a Relative Path by Setting a New Pathname with JavaScript

If the new page will be on the same domain we can use a relative redirect path making the program independent of the domain it is running on. Setting a new pathname on the location object will cause the browser to navigate to that location.

 

window.location.pathname = "/new";

 

Redirect to the Previous Page with JavaScript

We can use the browser window History API to navigate to the previous page.

 

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

 

Conclusion

You now know several different ways to redirect a page to a new location using JavaScript.

redirect