0

I need to trigger an method while closing the window. For that I tried to put an alert statement and it is working fine both in IE and FIREFOX . But not working in chrome. Please help me on this..

$(window).bind('beforeunload', function(){
   alert ("before unload")
});
Arun
  • 3,440
  • 11
  • 60
  • 108
  • check this: http://stackoverflow.com/questions/9626059/window-onbeforeunload-in-chrome-what-is-the-most-recent-fix – abhiklpm Nov 13 '13 at 08:09
  • you can check for `useragent` and execute the relevant code block. or check this http://stackoverflow.com/questions/1997956/javascript-window-close-event-rather-than-unload-event-for-all-browsers – New Developer Nov 13 '13 at 08:30

1 Answers1

3

You can't do that. There's no way in modern browsers to reliably do a non instant operation on the beforeunload event (especially, all operations involving a query are usually prevented). It's a security measure : nothing that may delay or prevent the user-required closing of a window is acceptable.

You need to change the logic of your application. Modern AJAX applications must continuously save the data that need saving or provide a visible way to launch the save, they can't wait for the window to be closing. And you have to manage your sessions life-cycle server-side without relying on the browser issuing a log-off.

Regarding the alert and Chrome, here's an extract from the MDN :

Since 25 May 2011, the HTML5 specification states that calls to window.showModalDialog(), window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event.

It's probable that more and more browsers will prevent this alert which is just painful most of the times.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • do u mean to say that window.unload itself wont work ??? or just the alert part within window.unload wont work ? – Arun Nov 13 '13 at 08:03
  • actually i need to trigger log-off functionality while the window is getting closed .. – Arun Nov 13 '13 at 08:03
  • Inside the event handler you may (not 100% reliably) do small actions, like changing localStorage, you can't do an ajax call and you can't be sure you can make an alert. – Denys Séguret Nov 13 '13 at 08:04
  • And it makes no sense to trigger a log-off when the window is closing. You have to manage your sessions life-cycle server side without relying on the browser issuing a log-off. – Denys Séguret Nov 13 '13 at 08:05
  • ok.. i wil explain .. we have a funcionality such way that, while logging off, some details from the table would be deleted... this is working fine in IE and not in chrome. thats the problem ..not just session killing.. we perform some data deletion in table – Arun Nov 13 '13 at 08:06
  • This is a very bad architecture. You can't rely on the browser sending a log-off signal. Always assume the network or browser can disappear. This means for example your server must clean the sessions that weren't recently hit. – Denys Séguret Nov 13 '13 at 08:08