Can we restrict a window close event?

4 posts, 0 answers
  1. Dhamodharan
    Dhamodharan avatar
    300 posts
    Member since:
    Sep 2010

    Posted 04 Sep 2013 Link to this post

    Hi,
    Can we restrict a window close event? It should show a alert message and not close the window.





    Thanks
  2. Shinu
    Shinu avatar
    17764 posts
    Member since:
    Mar 2007

    Posted 05 Sep 2013 Link to this post

    Hi Dhamodharan,

    Please have a look at the following JavaScript:

    JavaScript:
    <script type="text/javascript">
        window.onbeforeunload = function (e) {
            alert("Any unsaved data will be lost.");
        };
    </script>

    Hope this helps,
    Shinu.
  3. Dhamodharan
    Dhamodharan avatar
    300 posts
    Member since:
    Sep 2010

    Posted 05 Sep 2013 Link to this post

    Hi Shinu,
    Thanks for your quick response. I tried this , the alert is shown and when i click the alert the window get closed. my requirement is the restrict the Window close, after the alert shown the windows should be open.








    Thanks
  4. Shinu
    Shinu avatar
    17764 posts
    Member since:
    Mar 2007

    Posted 06 Sep 2013 Link to this post

    Hi Dhamodharan,

    As far as I know, the only possible solution is to use the onbeforeunload. It wont completely restrict the user from closing the browser window which is not possible either from client side or from server side but it will prompt the user asking them whether they really want to leave or stay back, which is probably the best cross browser solution you can manage. As per the code the message returned will also be displayed along with the standard browser "Leave Page" confirm (the message wont be displayed in Firefox).  Please check the updated code and have a look at the attached screenshot.

    JavaScript:
    <script type="text/javascript">
        window.onbeforeunload = confirmExit;
        function confirmExit() {
            return "Any unsaved data will be lost";
        }
    </script>

    Thanks,
    Shinu.
Back to Top