JavaScript Page Redirect

Page redirection is way to redirect from one webpage to another webpage. The redirected page can be on the same website or on a different website or web server.

window.location and window.location.href

In JavaScript, we can use many methods to redirect a webpage to another webpage. window.location is a object. It is used to get the current URL address and to redirect the browser to the new page. This property is of window object. The behaviour is same for both window.location and window.location.href.

Example : 

function redirectPage(){
       window.location = "http://www.google.com";
}
 redirectPage();

The page is redirected to google.

location.replace() :

The most frequently used is replace() method in window.location object, replace() method will replace the current document with new url and performs HTTP redirect.

Syntax :

window.location.replace("http://www.kfc.com");

location.assign() :

This method loads a new document in the browser window.

Syntax :

window.location.assign("http://www.kfc.com");

Difference between location.assign() and location.replace() :

location.replace() method deletes the current url from the document history. So, we cannot go back to the original document where as the location.replace() method loads a new document in the browser. To avoid this situation, we need to use location.assign() method.

location.reload() :

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

Syntax :

window.location.reload("http://shruthikatkoori.blogspot.com");

window.navigate() :

This is almost similar to window.location.href property i.e, assigning a new value. This is only available in MS Internet Explorer so better to avoid this in cross-browser development.

Syntax :

window.navigate("http://www.abc.com");

Redirection and Search Engine Optimisation :

If you want to notify the url forwarding to the SEO then need to add rel = "canonical" meta tag to your website head part because the search engines don't identify the JavaScript redirection.



No comments:

Post a Comment

Overview of AngularJS

AngularJS is an open source web application framework. It is now maintained by Google . The most of the code can be eliminated by using th...