JavaScript/JQuery : Redirect page examples

Notes for future references on how to redirect pages with JavaScript or JQuery. Sometimes, the simplest task is the hardest to remember :(

To simulate a HTTP redirect use replace :


To simulate a click on a link to redirect, use href :

 window.location.href = "//";
 document.location.href = '//';

To handle redirect based on referrer, first check if the referrer.indexOf and redirect based on the condition :

 // redirect back to main page URL if the referrer is from search engine or
 // someone types the domain in directly
 if(document.referrer.indexOf('') >= 0) {
 else {
 window.location.href = ''; 

To go back with checking referrer.indexOf, use :


JavaScript should be sufficient, but no harm to learn the JQuery equivalents :


By Adam Ng

IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.