Monday, February 4, 2008

Handling OnBeforeUnload Event Double Firing

IE 6.0 and 7.0 will fire onbeforeunload event twice if there is a link button on the ASP.Net page ( or in general an anchor with href set to a postback javascript). Here is the simple markup that "double firing" when postback happens:

<body onbeforeunload="alert();">
<form id="form1" runat="server">
<asp:LinkButton ID="LinkButton1" runat="server">LinkButton
</form>
</body>

The following javascript will make sure only the 1st Navigate-away event will invoke a message


var IsThe2ndNavAway=false;
function OBUL()
{
if (!IsThe2ndNavAway)
{
event.returnValue="Are you sure you want to lose your changes."
IsThe2ndNavAway=true;
setTimeout("IsThe2ndNavAway=false;",0)
}
}
Note that the 1st Nav-Away will execute the code to show message, etc. At the same time, 2nd will be blocked at function entry point since it is on the same thread as 1st Nav-Away.
As user dismiss the Message Box, the 2nd Nav-Away can no longer get into if-code block.
At the same time setTimeout will execute "IsThe2ndNavAway=false;" on a different thread so that the next round of "1st Nav-Away, 2nd Nav-Away" can contnue.

2 comments:

Soosai Raj said...

its not working when i use to close the page using asp:button
but it throws the warning and the page stays as it is if i click the browser Close button in IE it shows warning msg and closes help me to solve this

vini said...

nice post.. working well :-)