Report this

What is the reason for this report?

How to Redirect to Another Website with JavaScript?

Posted on November 12, 2020

Hello,

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

Thank you!



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

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.
0

Accepted 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

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.