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
+40.8k Golang : How to check if a string contains another sub-string?
+5.2k Javascript : Change page title to get viewer attention
+13.2k Golang : Date and Time formatting
+18.4k Golang : Set, Get and List environment variables
+6.8k Golang : Fibonacci number generator examples
+34.4k Golang : How to stream file to client(browser) or write to http.ResponseWriter?
+8.8k Golang : Inject/embed Javascript before sending out to browser example
+11.6k How to tell if a binary(executable) file or web application is built with Golang?
+17.1k Golang : When to use init() function?
+13.4k Golang : reCAPTCHA example
+16.9k Golang : XML to JSON example
+4.7k Fix Google Analytics Redundant Hostnames problem