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.7k Golang : File system scanning
+31.7k Golang : Proper way to set function argument default value
+19.5k Golang : untar or extract tar ball archive example
+4.5k Golang : Extract unicode string from another unicode string example
+28.4k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions
+8.1k Android Studio : Checkbox for user to select options example
+5.9k Golang : Sort words with first uppercase letter
+4.2k Linux : Disable and enable IPv4 forwarding
+14.8k Golang : Multi threading or run two processes or more example
+7.8k Golang : Print how to use flag for your application example
+16.9k Golang : Read input from console line
+5.4k Golang : Use modern ciphers only in secure connection