This is a migrated thread and some comments may be shown as answers.

Can we restrict a window close event?

3 Answers 237 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Dhamodharan
Top achievements
Rank 1
Dhamodharan asked on 04 Sep 2013, 05:14 PM
Hi,
Can we restrict a window close event? It should show a alert message and not close the window.





Thanks

3 Answers, 1 is accepted

Sort by
0
Shinu
Top achievements
Rank 2
answered on 05 Sep 2013, 05:06 AM
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.
0
Dhamodharan
Top achievements
Rank 1
answered on 05 Sep 2013, 12:25 PM
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
0
Shinu
Top achievements
Rank 2
answered on 06 Sep 2013, 06:33 AM
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.
Tags
General Discussions
Asked by
Dhamodharan
Top achievements
Rank 1
Answers by
Shinu
Top achievements
Rank 2
Dhamodharan
Top achievements
Rank 1
Share this question
or