Search code examples
javascriptasp.netmaster-pages

Javascript client & asp.net event handler timing issues - how to solve?


Simple web site with master page and multiple child pages.

In page_load, master page looks for session variable containing a value and if it's there, uses

Page.ClientScript.RegisterStartupScript(this.GetType(), "SessionAlert", "SessionExpireAlert(" + sessionTimeout + ");", true);

This kicks off a timeout alert, which works fine.

There is a server-side button on one child page that effectively ends the user interaction on the page and leaves a message stating "go and log in again if you want to do more stuff". When this button is clicked, I want to clear out the session variable (easy) and end the running timeout warning alert script (not so easy).

As the Master "page_load" event fires BEFORE the button handler, at the time the page reloads, it restarts the timeout script. When it hits the button event handler and clears the session variable, it's too late as the script is already running.

I've tried using "registerclientscriptblock" to inject immediate javascript to call the "clearTimeout()" client side function I have, but it doesn't seem to be able to find the function which exists on the master page and errors.

This seems to be a classic "chicken and egg" scenario and I can't see the wood for the trees. Could someone please point me in the right direction here before I drive myself mad!?

edited to add bit of javascript code:

Currently the master page function "SessionExpireAlert" referenced by the page_load code contains among other things this:

                 window.updateInterval = setInterval(function () {
                     seconds--;
                     document.getElementById("idleTime").innerHTML = convertTime(seconds);
                     document.getElementById("expireTime").innerHTML = convertTime(seconds);
                 }, 1000);

Solution

  • RegisterStartupScript will add the script to the end of the body, so the DOM is ready when it runs. As long as you always use RegisterStartupScript after that then the scripts will be added and executed in the order you create them.

    Basically, RegisterClientScriptBlock is most likely going to place the script before any scripts added with RegisterStartupScript.