22

I have a chat application, I want that whenever user accidentally or manually closes the browser ,he should get an alert so that various clean up operations could be carried out. I have more thing i itried to use on before event but I want that to be used for a particular web page as all other web pages are also called on before load. Please help

Jonik
  • 80,077
  • 70
  • 264
  • 372
pradeep
  • 1,047
  • 3
  • 20
  • 24

4 Answers4

24

This is not really a JQuery thing, I use this functions:

function setConfirmUnload(on) {
    window.onbeforeunload = (on) ? unloadMessage : null;
}

function unloadMessage() {
    return "Are you sure you want to leave this page";
}

Then, at any time you can call

setConfirmUnload(true) to enable the confirmation or false if you want to allow them to close the screen without a warning (if you have a close button for instance).

Ariel Popovsky
  • 4,787
  • 2
  • 28
  • 30
23

We should prevent or prompt user that on performing these actions he will lose his data.

  1. Click on back browser button.
  2. Click on refresh browser button.
  3. Click on close button of browser.
  4. Click of forward browser button.
  5. Keyboard stroke- Alt+F4 (Close)
  6. Keyboard stroke- F5 (Refresh)
  7. Keyboard stroke-CTRL+ F5 (Refresh)
  8. Keyboard stroke-Shift+ F5 (Refresh)
  9. Change of url
  10. Or anything that cause postback other than your particular submit button.

To explain that I have used two textboxes, one Asp.net submit button with id TestButton. Other postback controls that I have taken are One other asp.net button,one checkbox with autopostback property true,one dropdownlist with autopostback property true. Now I have used all these postback controls so that to show you that we also need to show promt to user about the data lose when user perform actions on these controls. On submit button we will not show the prompt as we have to submit the data with that control action.Here is the sample code.I have set window.onbeforeunload method on controls change.

<html >
<head id="Head1">
    <title></title>

    <script type="text/javascript"
            src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

    <script type="text/javascript">
        $(function()
        {
            // Prevent accidental navigation away
            $(':input').bind(
                'change', function() { setConfirmUnload(true); });
            $('.noprompt-required').click(
                function() { setConfirmUnload(false); });

            function setConfirmUnload(on)
            {
                window.onbeforeunload = on ? unloadMessage : null;
            }
            function unloadMessage()
            {
                return ('You have entered new data on this page. ' +
                        'If you navigate away from this page without ' +
                        'first saving your data, the changes will be lost.');
            }

            window.onerror = UnspecifiedErrorHandler;
            function UnspecifiedErrorHandler()
            {
                return true;
            }

        }); 

    </script>

</head>
<body>
    <form id="form1" name="myForm" runat="server">
    <div>
        First Name :<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
        <br />
        Last Name :<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
        <br />
        IsMarried :<asp:CheckBox ID="CheckBox1" runat="server" /><br />
        <br />
        <asp:Button runat="server" ID="TestButton" Text="Submit" CssClass="noprompt-required" /><br />
        <br />
        <br />
        <br />
        <br />
        <asp:Button runat="server" ID="AnotherPostbackButton" Text="AnotherPostbackButton"
             /><br />
        <br />
        <asp:CheckBox runat="server" ID="CheckboxWhichCausePostback" Text="CheckboxWhichCausePostback"
            AutoPostBack="true" /><br />
        <br />
        DropdownWhichCausePostback<asp:DropDownList runat="server" ID="DropdownWhichCausePostback"
            AutoPostBack="true">
            <asp:ListItem Text="Text1"></asp:ListItem>
            <asp:ListItem Text="Text2"></asp:ListItem>
        </asp:DropDownList>
        <br />
        <br />
    </div>
    </form>
</body>

Above I have used:

$('.noprompt-required').click(function() { setConfirmUnload(false); });

What I have done in this line is I am calling setConfirmUnload method and passing false as argument which will set the window.onbeforeunload to null. So what that means is on any control where you want that user should not be prompted, give that control the class .noprompt-required and leave other as it is.

Hulk1991
  • 3,079
  • 13
  • 31
  • 46
Raghav
  • 8,772
  • 6
  • 82
  • 106
  • I voted for this, but... it doesn't work in IOS (iPad/iPhone), which is a bummer. – Michael Apr 18 '13 at 02:30
  • 1
    This solution triggers even when the form is actually submitted. It is unusable. – festiv Feb 01 '16 at 16:13
  • It does not work. I tried closing the browser's close button –  Nov 07 '17 at 10:35
  • Does not work; the message will be the standard one in firefox & chrome. It cannot be set, so spare the extra fluff, all you need is the very simple onbeforeunload event handler bit to return something. – Steve Horvath Jul 27 '21 at 04:11
8

You can try the unload event:

$(window).unload( function () { alert("Bye now!"); } );

http://docs.jquery.com/Events/unload

I'm guessing this cleanup is on the client only. It would be interesting to know the nature of these "cleanups".

James Wiseman
  • 29,946
  • 17
  • 95
  • 158
  • 2
    "interesting to know the nature" indeed. they'd better not be things the host needs, because no matter what kind of cleanup you can force on unload, you won't catch it if the browser is killed from task manager or the user's PC crashes... – jwl Aug 07 '09 at 13:06
  • I was also implying that some cleanup may also be required on the server. Something that could possibly be handled in the event of a browser kill from the task manager. – James Wiseman Aug 07 '09 at 13:39
  • This will alert the user, but there is nothing they can do to return to the page. I think the word "accidentally" in his question implies a type of alert that SO uses. – Josh Stodola Aug 07 '09 at 18:13
0

You may try this with ajax

$(window).unload( function () { alert("AJAX function to do required job"); } );
San
  • 632
  • 4
  • 13