JavaScript – How to redirect a page

In JavaScript, we can use either location.replace() or location.href to redirect a page. Normally, we use location.replace() to simulate an HTTP redirect.


<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
</head>

<body>

    <h1>JavaScript - How to redirect a page</h1>

    <h3>1. location.replace</h3>
    <button onclick="httpRedirect()">location.replace</button>

    <h3>2. location.href</h3>
    <button onclick="mouseClick()">location.href</button>

    <script>
        //  Simulate an HTTP redirect
        function httpRedirect() {
            location.replace("https://www.mkyong.com")
        }

        // Simulate a mouse click
        function mouseClick() {
            location.href("https://www.yahoo.com")
        }
    </script>

</body>

</html>

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar