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
+7.5k Linux : How to fix Brother HL-1110 printing blank page problem
+11.4k Golang : How to use if, eq and print properly in html template
+12.3k Golang : Split strings into command line arguments
+28.3k Golang : Connect to database (MySQL/MariaDB) server
+7.6k SSL : How to check if current certificate is sha1 or sha2 from command line
+21.9k Golang : Convert string slice to struct and access with reflect example
+46.7k Golang : Marshal and unmarshal json.RawMessage struct example
+5.2k Swift : Convert (cast) Float to Int or Int32 value
+8.4k Golang : Convert word to its plural form example
+3.5k Golang : Fix go-cron set time not working issue
+10.2k Golang : Compare files modify date example
+51.5k Golang : Check if item is in slice/array