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
+13.9k Golang : Reverse IP address for reverse DNS lookup example
+19.1k Golang : Check if directory exist and create if does not exist
+8k Golang : Routes multiplexer routing example with regular expression control
+7.8k Swift : Convert (cast) String to Float
+32.5k Golang : Regular Expression for alphanumeric and underscore
+5.9k Javascript : Get operating system and browser information
+25.9k Mac/Linux and Golang : Fix bind: address already in use error
+9k Golang : Serving HTTP and Websocket from different ports in a program example
+12.4k Golang : Exit, terminating or aborting a program
+7.2k Golang : How to detect if a sentence ends with a punctuation?
+5.2k Unix/Linux/MacOSx : How to remove an environment variable ?
+15.9k Golang : Generate universally unique identifier(UUID) example