How to redirect to another webpage?
Solution 1:
One does not simply redirect using jQuery
jQuery is not necessary, and
window.location.replace(...) will best simulate an HTTP redirect.window.location.replace(...) is better than using window.location.href, because replace()does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.If you want to simulate someone clicking on a link, uselocation.hrefIf you want to simulate an HTTP redirect, uselocation.replace
ContentMiddleAd
For example:// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
ContentMiddleAd
Solution 2:
WARNING: This answer has merely been provided as a possible solution; it is obviously not the best solution, as it requires jQuery. Instead, prefer the pure JavaScript solution.
$(location).attr('href', 'http://stackoverflow.com')
Solution 3:
Standard "vanilla" JavaScript way to redirect a page:window.location.href = 'newPage.html';ContentMiddleAd
If you are here because you are losing HTTP_REFERER when redirecting, keep reading:
The following section is for those using
HTTP_REFERER as one of many secure measures (although it isn't a great protective measure). If you're using Internet Explorer 8 or lower, these variables get lost when using any form of JavaScript page redirection (location.href, etc.).Below we are going to implement an alternative for IE8 & lower so that we don't lose HTTP_REFERER. Otherwise you can almost always simply usewindow.location.href.
Testing against
HTTP_REFERER (URL pasting, session, etc.) can be helpful in telling whether a request is legitimate. (Note: there are also ways to work-around / spoof these referrers, as noted by droop's link in the comments)
Simple cross-browser testing solution (fallback to window.location.href for Internet Explorer 9+ and all other browsers)
Usage:
redirect('anotherpage.aspx');function redirect (url) {
var ua = navigator.userAgent.toLowerCase(),
isIE = ua.indexOf('msie') !== -1,
version = parseInt(ua.substr(4, 2), 10);
// Internet Explorer 8 and lower
if (isIE && version < 9) {
var link = document.createElement('a');
link.href = url;
document.body.appendChild(link);
link.click();
}
// All other browsers can use the standard window.location.href (they don't lose HTTP_REFERER like Internet Explorer 8 & lower does)
else {
window.location.href = url;
}
}
Solution 4:
ContentMiddleAd
But if someone wants to redirect back to home page then he may use the following snippet.
window.location = window.location.host
It would be helpful if you have three different environments as development, staging, and production.
You can explore this window or window.location object by just putting these words in Chrome Console or Firebug's Console
go
ReplyDeletelook at more info
click over here
see this site