Redirect is nothing but a mechanism of sending search engines and users on a different URL from the original one. The redirected page can be on the same server or on a different server. It can also be on the same website or on different websites.
Redirect to a different page that was not requested is done by using ECMAScript 2015 or ES6. There are several methods used for performing page redirection, such as location.href, location.replace(), and many more.
Let us try to understand some of the methods in JavaScript that are used for page redirection.
window.location object is a property of the window object. There are several methods to redirect a web page. Almost all methods are related to the window.location object.
It can be used for getting the address of the current URL or the web address. The window.location object can be written without adding the window prefix.
window.location = " https://www.rookienerd.com/";
It is one of the commonly used window.location object. It is used for replacing the original document with a new one.
In this method, we can pass a new URL, and then it will perform an HTTP redirect.
window.location.replace("new URL");
window.location.replace("https://www.rookienerd.com/");
This method is used to load a new document within the browser window.
The difference between the location.assign() and location.replace() method is that the replace() method deletes the current URL from the history of the document. So, it will not be possible to perform back navigation. In this case, we cannot use the back button.
To avoid this, we should use the location.assign() method because it loads a new browser document.
window.location.assign("https://www.rookienerd.com/");
This method is used for reloading the current document dynamically. We can specify a Boolean parameter, either true or false. It the parameter value is true, then the method will force the browser to reload the page from the server. But if it is false or unspecified, then the browser may reload the page from the cache.
window.location.reload("https://www.rookienerd.com/");
This method is only available in Internet explorer because all the other browsers remove this method. It is similar to assigning a new value to the window.location.href property.
window.navigate("https://www.rookienerd.com/");
Generally, search engines do not analyze the JavaScript to check the redirection. So, if it is required to notify the search engines (SEO) about the URL forwarding, we need to add the rel = "canonical" tag within the head section of the web page.
<link rel = "canonical" href = "https://www.rookienerd.com/" />