How do I redirect to another webpage? How do I redirect to another webpage? javascript javascript

How do I redirect to another webpage?


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, use location.href

If you want to simulate an HTTP redirect, use location.replace

For example:

// similar behavior as an HTTP redirectwindow.location.replace("http://stackoverflow.com");// similar behavior as clicking on a linkwindow.location.href = "http://stackoverflow.com";


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')


Standard "vanilla" JavaScript way to redirect a page

window.location.href = 'newPage.html';

Or more simply: (since window is Global)

location.href = 'newPage.html';

If you are here because you are losing HTTP_REFERER when redirecting, keep reading:

(Otherwise ignore this last part)


The following section is for those using HTTP_REFERER as one of many security 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 use window.location.href.

Testing against HTTP_REFERER (URL pasting, session, etc.) can help tell 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;     }}