Hello,

What is the best way of redirecting a user to another website or page using pure JavaScript?

Thank you!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
1 answer

Hey there,

One way to do that would be to use the location.href. Here’s an example:

window.location.href = "https://digitalocean.com";

Here is a quick demo:

Redirect user to another page using JavaScript

If you want to redirect the user to a specific page on your site just specify the page itself:

window.location.href = "some-page.html";

Another option would be to use location.replace instead:

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

One of the main differences between location.replace and location.href is that with location.replace the user’s current page will not be saved in the session, which means that your users will not be able to go back to the old page with the ‘Back’ button.

If you are new to JavaScript I would highly recommend this tutorial series here:

https://www.digitalocean.com/community/tutorial_series/how-to-code-in-javascript

Hope that this helps!
Regards,
Bobby

Submit an Answer