Question

How to redirect a user from one page to another using JavaScript?

3 Answers

window.location.href = "http://newUrl.org";

It is similar to clicking on a link. As a side note.. you can use either of the following two, both are same in terms of behavior.

window.location = "http://newUrl.org";

window.location.href = "http://newUrl.org";

The href property sets or returns the entire URL of the current page. The window.location returns a Location object. If the href parameter is not set, window.location defaults to change the value of href.


To simulate an HTTP redirect, use

window.location.replace("http://example.org")


We know that the search engines don't analyse the JavaScript code and therefore cannot see the redirection by default. However, if you want to notify them about the redirection, add the rel="canonical" meta tag to your website.

Also, you can add a noscript section with a HTML refresh meta tag in it.

<link rel="canonical" href="http://example.org/"/>
<noscript>
    <meta http-equiv="refresh" content="0;URL=https://example.org/">
</noscript>