onbeforeunload event is fired on click

onbeforeunload browser’s event fires when the window is about to navigate to another page or about to be closed. So why why would it fire when you click to call a JavaScript function that does neither of the two?

If your have your click setup similar to something like this:

<a href='javascript:doStuff()'>Click to do something</a>

or, if you’re using ASP.NET’s HyperLink control:

<asp:HyperLink ID="xhypMuLink" runat="server" NavigateURL="javascript:doStuff()">
   Click to do something

And your “doStuff()” function doesn’t redirect or closes the window – you’d expect it just do its stuff and that’s it. But in addition to it, or rather before it onbeforeunload event fires, so if you have some code in the event handler – it will be executed, which in this case is undesirable.

Why does it happen? Even though you’re calling just a local JavaScript function, you’re using navigation attributes href/NavigateURL to do so, so technically window does navigate to another page.

The solution? Instead of href/NavigateURL attributes use onclick to call JavaScript functions – many elements support them, including hyperlinks. But you won’t even have to use hyperlinks, for example the markup above can be rewritten using simple SPAN:

<span style="color:blue;text-decoration:underline;cursor:hand" onclick="doStuff()">
   Click to do something

Notice style attribute used to simulate hyperlink appearance including underline and hand cursor.

Leave a Reply

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