2

I searched for this question in various places, but all that they mention is the use of Javascript window.unload and window.onbeforeunload. Also it doesn't work in Chrome most of the times as it gets blocked.

Then how does google manage to do it. If we are composing a mail and by mistake close the tab, google prompts us by a "Are you sure?" box.

Can somebody help me out?

What actually I want to do is to ask confirmation of the user, when he is filling in the form and by mistake clicks on tab close. If yes, I allow him to navigate away else he stays on the page & continues to fill his form.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
gopi1410
  • 6,567
  • 9
  • 41
  • 75
  • 1
    I do not know if google has another way to detect this. But your both functions mentioned are for this case... – Neysor Mar 30 '12 at 10:38

3 Answers3

7

I tested and the example posted on MDN works clearly in Chrome.

<script>
    window.onbeforeunload = function (e) {
        e = e || window.event;

        // For IE and Firefox prior to version 4
        if (e) {
            e.returnValue = 'Any string';
        }

        // For Safari
        return 'Any string';
    };

    function formSubmit() {
      window.onbeforeunload = null; 
   }
</script>

...

   <form onsubmit="formSubmit()">...</form>

This way a dialog opens that will not be blocked by a popup blocker as it is originated from a user click.

Peter Aron Zentai
  • 11,482
  • 5
  • 41
  • 71
  • thanks a lot. :) still have to learn a lot about js events.. Any good reference for it? – gopi1410 Mar 30 '12 at 10:49
  • One more thing. If I have a form in the page, & when the user clicks on submit button, it still asks for confirmation. But I dont want confirmation on form submission. How to correct this? – gopi1410 Mar 30 '12 at 10:57
2

If you only want to ask a user if they want to leave the page when they've changed anything in the forms on the page, have a look at PageHasFormChanges. Keep in mind that I developed it for use it on very simple pages, with only one or two forms.

PageHasFormChanges: A jQuery plugin to check if anything has changed in any form on a page, and warn the user before leaving the page.

You don't need to do anything, but load the script on your page. You can change the defaults though:

JoelPurra.PageHasFormChanges.setOptions({
    leavingPageWarningMessage: "Are you sure?"
});

If you're using ajax to submit your forms, you could consider setting resetWarningOnPreventedSubmit to true.

Joel Purra
  • 24,294
  • 8
  • 60
  • 60
1

you can use the jquery unload function:

$(window).unload(function() {
  alert('Handler for .unload() called.');
});
Sujit Agarwal
  • 12,348
  • 11
  • 48
  • 79
  • this is also blocked by chrome. (as it is equivalent of js onunload). Anyways thanks, the problem is now solved, thanks to peter. – gopi1410 Mar 30 '12 at 10:51