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
+21.1k Golang : Sort and reverse sort a slice of strings
+6.8k Golang : Output or print out JSON stream/encoded data
+9.5k Golang : Accessing content anonymously with Tor
+10.9k Golang : How to transmit update file to client by HTTP request example
+7.7k Golang : Mapping Iban to Dunging alphabets
+6.7k Golang : Derive cryptographic key from passwords with Argon2
+8.8k Golang : Take screen shot of browser with JQuery example
+33k Golang : How to check if a date is within certain range?
+5.2k Golang : Convert lines of string into list for delete and insert operation
+21.3k Golang : How to get time zone and load different time zone?
+5.7k Fix yum-complete-transaction error
+14.6k Golang : Execute function at intervals or after some delay