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
+12.9k Golang : Pass database connection to function called from another package and HTTP Handler
+12.5k Golang : Display list of countries and ISO codes
+5.9k Linux/Unix/PHP : Restart PHP-FPM
+7k Golang : Pat multiplexer routing example
+6k Golang : Launching your executable inside a console under Linux
+20.7k Golang : Pipe output from one os.Exec(shell command) to another command
+13k Swift : Convert (cast) Int or int32 value to CGFloat
+8.5k Golang : Auto-generate reply email with text/template package
+28.8k Golang : Change a file last modified date and time
+22.6k Golang : Convert Unix timestamp to UTC timestamp
+6.3k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+33.2k Golang : How to check if a date is within certain range?