javascript – how to redirect temporarily to one page before going to another on button click-ThrowExceptions

Exception or error:

I am working on a website for a client. for the backend I am using Django. In the webpage, there exists a button which when clicked loads another page. But the client wants the program to be such that when the button is clicked the another page should be loaded first internally and then the original page should be loaded.

For example suppose the page with the button is PAGE A, the target page is PAGE B, and the temporary page is PAGE C.

When the button is clicked, the url should change to PAGE C first and then PAGE B should be loaded.

Not sure why my client would want that, but they do. I looked at this code

<meta http-equiv="refresh" content="0; URL=the_webpage_to_be_loaded"/>

This code redirects the page to the target page immediately on page refresh. Instead this should happen only when the button is clicked and only for a moment.

This is the code for the button

<a href="{% url 'redirect_page_1' %}" class="btn btn-lg mb-5 redirect_submit">redirect on click</a>
How to solve:

There is a javascript solution for this, for the demo, I have created 3 html files.

  1. index.html => initial html. ( in your case a.html )
  2. b.html => This is where the page loads for a sec and then redirect to c.html
  3. c.html => This is the final page

index.html file is

<body>
  <h2>This is the first html</h2>
  <div>
    <button type="button" onclick="goTo()">Go to html 3</button>
  </div>
</body>
<script>
  function goTo(){
    window.location.replace('b.html?q=c.html')
  }
</script>

b.html file is

<body>
    <h2>This is the second html</h2>
</body>
<script>
    document.addEventListener("DOMContentLoaded", function(){
        var url_string = window.location.href;
        var url = new URL(url_string);
        var redirectUrl = url.searchParams.get("q");
        setTimeout(function(){
            window.location.replace(redirectUrl)
        },1000)
    });
</script>

c.html file is

<body>
    <h2>this is the third html</h2>
</body>

Here what it actually does is, on button click we will call a function, and the function will redirect to temporary html file ( b.html ) with a query parameter to which url should it redirect from b.html.

In b.html, there is a javascript function which invokes after the page load and it will get the query params from the url and then redirect to the params url, in this case c.html.

Try creating 3 html files and let me know if it is solved. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *