How to redirect to another page in Javascript

January 21, 2019

This question often comes up, and people are usually wondering whether jQuery is needed for redirecting to a different page. The answer is no.

Compatible with most browsers including IE9 & higher:

// Simulating an HTTP redirect
window.location.replace("https://google.com");

// Simulating a user clicking a link
window.location.href = "https://google.com";

IE8 & lower:

const redirect = url => {
    const userAgent = navigator.userAgent.toLowerCase();
    const usingIE = userAgent.indexOf("msie") !== -1;
    const userAgentVersion = parseInt(userAgent.substr(4, 2), 10);

    if (usingIE && userAgentVersion < 9) {
        // Create anchor link element and add to page
        const anchor = document.createElement('a');
        anchor.href = url;
        document.body.appendChild(anchor);

        // Click on link
        anchor.click();
    } else { 
        window.location.href = url; 
    }
}