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

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments