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
+8.2k Golang : How to check variable or object type during runtime?
+27k Golang : Convert CSV data to JSON format and save to file
+29.5k Golang : How to get HTTP request header information?
+8.3k Golang : Convert(cast) []byte to io.Reader type
+9.1k Golang : Scramble and unscramble text message by randomly replacing words
+17.7k Golang : Convert IPv4 address to decimal number(base 10) or integer
+7.5k Golang : get the current working directory of a running program
+13.4k Golang : How to determine if a year is leap year?
+19.5k Golang : Append content to a file
+5.8k Golang : Measure execution time for a function
+16.8k Golang : How to tell if a file is compressed either gzip or zip ?
+17.2k Golang : Clone with pointer and modify value