16

Possible Duplicate:
How to prevent closing browser window?

I want to show an alert message "Please logout before closing the window" with an logout button, when an user tries to close the window and after clicking on logout button the window can be closed. How to achieve this?

Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
Mak
  • 191
  • 1
  • 2
  • 11
  • You can't *prevent* someone from closing their browser. You can give them a warning, which lets them continue or cancel. Check out the onbeforeunload event. – Mike Christensen Nov 05 '12 at 06:41
  • http://stackoverflow.com/questions/333665/javascript-to-get-an-alert-when-closing-the-browser-window – Nirav Ranpara Nov 05 '12 at 06:42
  • 1
    Look to the right, next time read one of them. This is a FAQ! Use `window.onbeforeunload=function() { return 'Please save'}` – mplungjan Nov 05 '12 at 06:42
  • See this http://stackoverflow.com/questions/1997956/javascript-window-close-event-rather-than-unload-event-for-all-browsers and http://stackoverflow.com/questions/1631959/browser-window-close-event – Hkachhia Nov 05 '12 at 06:42

3 Answers3

14

Another implementation you can try:

<html>
  <head>
    <script type="text/javascript">
      window.onbeforeunload = function() {
          return "Did you save your stuff?"
      }
    </script>
  </head>
  <body>

  </body>
</html>

Update

As mentioned in comment by @JohnnyFun "Starting with Firefox 44, Chrome 51, Opera 38 and Safari 9.1, generic message will be displayed for different browsers and cannot be customized".

Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
  • 6
    Using this code I always see the same message in when closing tab in Chrome: "Do you want to leave this site? Changes you made may not be saved." – R.S.K Aug 22 '16 at 19:56
  • 3
    @R.S.K mdn mentions: "Starting with Firefox 44, Chrome 51, Opera 38 and Safari 9.1, a generic string not under the control of the webpage will be shown instead of the returned string. For example, Firefox displays the string "This page is asking you to confirm that you want to leave - data you have entered may not be saved." (See bug 588292), and Chrome displays the string "Do you want to leave this site? Changes you made may not be saved"" https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload – JohnnyFun May 14 '18 at 21:53
4
window.onbeforeunload = function() {
    return "Are you sure?";
 };

Try this it.

Amit Garg
  • 3,867
  • 1
  • 27
  • 37
1

There is not as such close event available in Javascript. You can give message onUnload event. But that doesn't prevent application from closing. This function will execute when user click on any link, submitting the form etc.

window.onunload=function(){SomeJavaScriptCode};

For reference: http://www.w3schools.com/jsref/event_onunload.asp

Chinmayee G
  • 7,947
  • 2
  • 31
  • 41