Twitter: raymondcamden


Address: Lafayette, LA, USA

Detect window close/reload versus exit

09-14-2011 14,711 views jQuery, JavaScript 10 Comments

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.

view plain print about
1<html>
2
3<head>
4<script type="text/javascript"
5src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
6<script>
7$(window).bind('click', function(event) {
8 if(event.target.href) $(window).unbind('beforeunload');
9});
10$(window).bind('beforeunload', function(event) {
11 return 'pls save ur work';
12});
13</script>
14</head>
15
16<body>
17
18<a href="test2.cfm">reload</a>
19
20</body>
21</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?

10 Comments

  • Commented on 09-14-2011 at 11:12 AM
    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!
  • Josh #
    Commented on 09-14-2011 at 11:59 AM
    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
    }
    });
  • Mike #
    Commented on 09-14-2011 at 1: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
  • Commented on 09-14-2011 at 1:26 PM
    I tried FF and Chrome I think. I don't test in IE if I can help it.
  • Commented on 09-14-2011 at 2: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!
  • Commented on 09-14-2011 at 3:00 PM
    I wrote up this javascript file http://apps.jin-park.com/js/form_saver.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.
  • Bill Tudor #
    Commented on 09-15-2011 at 5:52 AM
    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?
  • prashant #
    Commented on 10-16-2011 at 12: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.
  • Commented on 10-21-2011 at 3:48 PM
    You got me there then. YOu could always switch to using a solution that stores the form stuff in Local Storage behind the scenes.
  • prashant #
    Commented on 12-14-2011 at 8:00 PM
    hi,

    thanks for all help.
    finally its working for me.
    this is also a good reference
    http://msdn.microsoft.com/en-us/library/ms536907%2...

    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

Post Reply

Please refrain from posting large blocks of code as a comment. Use Pastebin or Gists instead. Text wrapped in asterisks (*) will be bold and text wrapped in underscores (_) will be italicized.

Leave this field empty