ES6 - Page Redirect


Redirect is a way to send both users and search engines to a different URL from the one they originally requested. Page redirection is a way to automatically redirect a web page to another web page. The redirected page is often on the same website, or it can be on a different website or a web server.

JavaScript Page Redirection

window.location and window.location.href

In JavaScript, you can use many methods to redirect a web page to another one. Almost all methods are related to window.location object, which is a property of the Window object. It can be used to get the current URL address (web address) and to redirect the browser to a new page. Both usages are same in terms of behavior. window.location returns an object. If .href is not set, window.location defaults to change the parameter .href.


<!DOCTYPE html> 
         function newLocation() { 
            window.location = ""; 

      <input type = "button" value = "Go to new location" onclick = "newLocation()"> 


The other most frequently used method is the replace() method of window.location object, it will replace the current document with a new one. In replace() method, you can pass a new URL to replace() method and it will perform an HTTP redirect.

Following is the syntax for the same.



The location.assign() method loads a new document in the browser window.

Following is the syntax for the same.


assign() vs. replace()

The difference between assign() and replace() method is that the location.replace() method deletes the current URL from the document history, so it is unable to navigate back to the original document. You can't use the browsers "Back" button in this case. If you want to avoid this situation, you should use location.assign() method, because it loads a new Document in the browser.


The location.reload() method reloads the current document in the browser window.

Following is the syntax for the same.



The window.navigate() method is similar to assigning a new value to the window.location.href property. Because it is only available in MS Internet Explorer, so you should avoid using this in cross-browser development.

Following is the syntax for the same.


Redirection and Search Engine Optimization

If you want to notify the search engines (SEO) about your URL forwarding, you should add the rel = "canonical" meta tag to your website head part because search engines don't analyze JavaScript to check the redirection.

Following is the syntax for the same.

<link rel = "canonical" href = "" />