Detect window close/reload versus exit

This post is more than 2 years old.

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>

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 HERE Technologies. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

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

Archived Comments

Comment 1 by Jason Presley posted on 9/14/2011 at 8:12 PM

I agree that checking if I want to leave a page is annoying and basically a newbie stunt just because you can. On the flip side however I create a number of internal applications that are very data heavy and making sure that people commit their changes before moving to something else would be huge. People get distracted with phone calls and meetings and forget to do something as simple as hit the save button. This is going to save a lot of time recreating lost work. Thanks Ray!

Comment 2 by Josh posted on 9/14/2011 at 8:59 PM

What I've done in the past when I needed to alert about unsaved data is I monitor the form for changes. If the user makes a change, I set an alert flag = true. If the user tries to leave the page by means other than a form submit, I fire the alert.
var alertFlag = false;
$("#yourForm :input").change(function(){
alertFlag = true;
});
$("#yourForm").submit(function(){
alertFalg = false;
});
$(window).bind('beforeunload', function(event) {
if(alertFlag){
//do some stuff
}
});

Comment 3 by Mike posted on 9/14/2011 at 10:19 PM

This is the only way I have found to do it, aside from like a modal window with jquery.

Does the jquery beforeunload work with both IE and FF? I know I ran into problems with IE not unbinding correctly so I had to do something differnt with IE, then again I was not using jquery to unbind for the beforeunload

Comment 4 by Raymond Camden posted on 9/14/2011 at 10:26 PM

I tried FF and Chrome I think. I don't test in IE if I can help it.

Comment 5 by Ben Nadel posted on 9/14/2011 at 11:03 PM

That's a pretty clean approach. In the "click" event, you could also throw up a prompt() and cancel the event behavior too. I only add that as I am not sure if all the browsers support the ability to "block" an unload event? Not sure, haven't tried. Cool idea, though!

Comment 6 by Jin Park posted on 9/15/2011 at 12:00 AM

I wrote up this javascript file http://apps.jin-park.com/js... for the same reason. There occasions when even if a form is changed, you might want to allow them to get out (hitting a cancel button, reset button, etc). It's not very sexy since it doesn't use jQuery, but it does the job. Tested in IE and Firefox.

Comment 7 by Bill Tudor posted on 9/15/2011 at 2:52 PM

Neat approach but cross-browser testing reveals some oddities. I have IE8, FF6.0.2 and Chrome (13...). IE appears to continue to run the beforeunload event, ignoring the .unbind? Things are a bit 'interesting when you Reload/Refresh or press F5. So maybe the reload event also needs trapping, and maybe we need to add some IE handling code?

Comment 8 by prashant posted on 10/16/2011 at 9:31 PM

still looking for a solution. not working in IE.
when i unbind "unload" event on a href clicks, submit clicks.
it does not fire unload event on browser close. It seems like its not binding unload event again on unload.

tried few other techinques but not success.

Comment 9 by Raymond Camden posted on 10/22/2011 at 12:48 AM

You got me there then. YOu could always switch to using a solution that stores the form stuff in Local Storage behind the scenes.

Comment 10 by prashant posted on 12/15/2011 at 7:00 AM

hi,

thanks for all help.
finally its working for me.
this is also a good reference
http://msdn.microsoft.com/e...

my gud code now. i am writing in steps

1. make allowprompt as true on page load
var allowPrompt = true;

2.
$(document).click(function(event) {
allowPrompt = false;
});

3.
$(document).ready(function() {
window.onbeforeunload = WarnUser;
});

4.
function WarnUser()
{

if(allowPrompt)
{
event.returnValue = "You have made changes. They will be lost if you continue.";
}
else
{
allowPrompt = true;
}
}

5. notes: i have few patch work here and there in code to avoid calling warnUser 2 times in a row.
--returning false on hyperlinks.
--location.reload was not working after using function on unload event so i used location.href insteaed of reload