Best ways to redirect page using JavaScript


Many time we need to redirect page or navigate to another page and this is quite easy using JavaScript. This can be done just by writing one line code.

// Just like HTTP redirects
window.location.replace("http://google.com");

// Just like clicking on a link
window.location.href = "http://google.com";

You can use any one of above and this works perfect but changing location using above code will lost HTTP_REFERER on IE8 and lower version browsers and this will create problem as you will not get url referrer on server. To fix this you can use following code. This code will simulate hyperlink click on IE 8 and below.

function navigate(url) {
    var ua        = navigator.userAgent.toLowerCase(),
        isIE      = ua.indexOf(\'msie\') !== -1,
        version   = parseInt(ua.substr(4, 2), 10);

    // IE8 and lower
    if (isIE && version < 9) {
        var link = document.createElement(\'a\');
        link.href = url;
        document.body.appendChild(link);
        link.click();
    }// for all other browsers
    else { window.location.href = url; }
}