in

simplusoft.net

another .NET open source community

iulia

Catch Web Browser Close Event - IE and Firefox

Sometime you need to catch the event of browser close. There are some situations when you
need to create some web application reports and you need to compute the totalm time spend by user
to visit each page, case when you need the exact moment when the user close the web page.
Or, you need to implement an engine for clear all the session variables used for a certain page.
To catch the close browser event we have to use different code in order to implement this in Internet Explorer and Firefox.
The html event is the same for both cases: onbeforeunload.But the javascript is different depending on the client browser; i have put the scripts only for the Internet Explorer and for the Mozilla Firefox.


 if (Request.Browser.Browser.IndexOf("IE") != -1)
        {
            this.ClientScript.RegisterStartupScript(
                 this.GetType()
                , Guid.NewGuid().ToString()
                , "document.body.onbeforeunload = function()"
                    + "{alert('window close - internet explorer');}\n", true);
        }
        else
            if (Request.Browser.Browser.ToLower().IndexOf("firefox") != -1)
            {
                HtmlGenericControl body = (HtmlGenericControl)this.FindControl("hostBody");
                if (body != null)
                    body.Attributes.Add("onbeforeunload", "alert('window close - firefox');");
            }


The problem is that we can not use the same method RegisterStartupScript when the client browser is Firefox, because this method does not have the expected execution as it is for Internet Explorer.
So, we are forced for Firefox to add attributes to the html body; for this we have to find programatically the html body, which in my example it is called "hostBody":

<body id="hostBody" runat="server">


The example can be downloaded from CatchBrowserCloseEvent.zip
 

Comments

No Comments
Simplusoft.net is a non-profit community dedicated to all .NET developers
Powered by Community Server (Non-Commercial Edition), by Telligent Systems