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("http://socketloop.com");
To simulate a click on a link to redirect, use href
:
window.location.href = "http://socketloop.com";
document.location.href = 'http://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','http://www.socketloop.com')
$(window).attr('location','http://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
+10.4k Golang : Flip coin example
+21.8k Golang : Match strings by wildcard patterns with filepath.Match() function
+36.1k Golang : Convert(cast) int64 to string
+5.1k Golang : Get FX sentiment from website example
+10.9k Google Maps URL parameters configuration
+7.2k Golang : Convert source code to assembly language
+13.7k Golang : concatenate(combine) strings
+15.3k Golang : Validate hostname
+11.6k Golang : Find and draw contours with OpenCV example
+7.7k Golang : Gomobile init produce "iphoneos" cannot be located error
+8.7k Golang : Build and compile multiple source files
+7.9k Golang : Get final or effective URL with Request.URL example