Detect window close/reload versus exit

This was an interesting question that came in from a reader:

I need to show a warning message on unload event of window. I'm using below code.

Problem is its coming on all hyperlinks, submit buttons. and if i try to trap event object, its coming as NULL.

The code he was using made use of the beforeunload window event. Now - let me state right away I’m hate sites that do something when I try to leave them. That being said - he was trying to prevent folks from losing work when closing a window or tab by mistake. At the same time though he didn’t want his safety code to run on simple clicks (or form submits). Here’s the method I came up with. It just supports ignoring links, not form submits, but I’ll throw it out there for folks to tear apart.

<html>

<head> <script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js”></script> <script> $(window).bind(‘click’, function(event) { if(event.target.href) $(window).unbind(‘beforeunload’); }); $(window).bind(‘beforeunload’, function(event) { return ‘pls save ur work’; }); </script> </head>

<body>

<a href=”test2.cfm”>reload</a>

</body> </html> </code>

Basically, I listen to both the click event and the beforeunload event. If a click happens (on a link), I unbind the beforeunload listener allowing the person to leave the page without getting the message. What do folks think? Ignoring the fact that it won't work on a form submit (but that's trivial enough to add), are there any other ways this can be improved?

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate for Extend by Auth0. He focuses on serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA https://www.raymondcamden.com

Comments