JavaScript Page Redirect

    Many websites use JavaScript for page redirection. In page redirection, when we click on page URL A, the browser redirects us to page URL B. Although you won't be seeing page redirection on every website, it is only implemented in specific situations when some old URL pages are dead, and the website has some new pages for the old content. Here are some of the main reasons why we would redirect the user from the actual page to a new page.

    • When you change your domain, and you want to redirect your all users from the older domain to the new domain, in that case, you can use the Page redirection.
    • You may have built different pages according to the browser compatibility or country region, there instead of redirecting the user using server-side technology, we can use JavaScript to redirect the user from the client-side.
    • Google has already indexed your page, now you have changed your domain, and you do not want to lose your traffic to the dead pages, there also you can use the page redirection so the user gets redirected to the new link when they try to access the old one.

    Working of Page-redirection

    To implement the page redirection we can use the JavaScript global window object's location property. Example 1 To implement the page redirection we can use a JavaScript function that will redirect the user to a new page when the user clicks on the button or link.

    <!DOCTYPE html>
    <html>
       <head>
          <script type = "text/javascript">
                function redirect() {
                   window.location = "https://www.techgeekbuzz.com";
                }
          </script>
       </head>
       <body>
          <p>Click the button for page redirection.</p>
          <button onclick = "redirect();"> Redirect to new page</button>
       </body>
    </html>

    Output

    Click the button for page redirection. Redirect to new page
    

    Example 2 In the above example, we created a static button that will redirect the user to the new page. But the above same tasks can be achieved using HTML anchor tag <a>. Let's write a JS script that will automatically redirect the user to a new page after 5 seconds of loading the page.

    <!DOCTYPE html>
    <html>
       <head>
          <script type = "text/javascript">
                function redirect() {
                   window.location = "https://www.techgeekbuzz.com";
                }
                document.write("Redirecting to new page in 5 sec..");
                setTimeout('redirect()', 5000);
          </script>
       </head>
       <body>
       </body>
    </html>

    Summary

    • By specifying the new URL link to the window.location property we can redirect the user to the new page.
    • JavaScript let us do the client-side redirection, to handle old dead links.