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
:
window.location.replace("//socketloop.com");
To simulate a click on a link to redirect, use href
:
window.location.href = "//socketloop.com";
document.location.href = '//socketloop.com';
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('socketloop.com') >= 0) {
history.go(-1);
}
else {
window.location.href = 'socketloop.com/welcome';
}
To go back with checking referrer.indexOf, use :
window.history.back()
window.history.go(-1)
JavaScript should be sufficient, but no harm to learn the JQuery equivalents :
$(location).attr('href','//www.socketloop.com')
$(window).attr('location','//www.socketloop.com')
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.
Advertisement
Tutorials
+5.3k Javascript : How to loop over and parse JSON data?
+12.2k Golang : 2 dimensional array example
+14.7k Golang : Get URI segments by number and assign as variable example
+39k Golang : How to iterate over a []string(array)
+36.2k Golang : How to split or chunking a file to smaller pieces?
+5.3k Unix/Linux/MacOSx : How to remove an environment variable ?
+19.7k Golang : Measure http.Get() execution time
+6.8k Android Studio : Hello World example
+17k Golang : XML to JSON example
+18.6k Golang : Iterating Elements Over A List
+10.8k Golang : Command line file upload program to server example
+18.6k Golang : Find IP address from string