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
+8.9k Golang : How to get username from email address
+7.4k Golang : How to execute code at certain day, hour and minute?
+9.1k Golang : Convert(cast) string to int64
+6.1k Grep : How to grep for strings inside binary data
+21.6k Golang : Match strings by wildcard patterns with filepath.Match() function
+18.6k Golang : Clearing slice
+5.3k Javascript : How to refresh page with JQuery ?
+19.4k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+8.6k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+5.4k Golang : Find change in a combination of coins example
+13.3k Golang : Get dimension(width and height) of image file