23

How I can capture event, close browser window, in jQuery or javascript ?

AlexC
  • 9,657
  • 17
  • 64
  • 98

4 Answers4

16

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

jQuery:

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

or javascript:

window.onunload = function(){alert("Bye now!");}
jeroen.verhoest
  • 5,173
  • 2
  • 27
  • 27
  • 1
    this event work and when I do refresh, but i need, only when I close the browser! – AlexC Jun 22 '09 at 07:52
  • 1
    @Alexander Corotchi: Why do you want to know when the user closes the browser? – Steve Harrison Jun 22 '09 at 08:19
  • 1
    In my application can work more users, And when 1 user close browser a need to execute a function for exclude this user from this application. – AlexC Jun 22 '09 at 08:51
  • This is not good enough. The only working solution is [Browser window close event](http://stackoverflow.com/questions/1631959/browser-window-close-event#1632004) – Pavel Hodek May 07 '12 at 10:53
  • 1
    Fail, when page change url call unload event, but no only close. unload != close. – e-info128 Oct 25 '12 at 18:08
9

You're looking for the onclose event.

see: https://developer.mozilla.org/en/DOM/window.onclose

note that not all browsers support this (for example firefox 2)

Jonathan Fingland
  • 56,385
  • 11
  • 85
  • 79
3

Events onunload or onbeforeunload you can't use directly - they do not differ between window close, page refresh, form submit, link click or url change.

The only working solution is How to capture the browser window close event?

Community
  • 1
  • 1
Pavel Hodek
  • 14,319
  • 3
  • 32
  • 37
-1

Men, use this:

if(myWindow.closed){
    callback();
    return;
}
Brunno
  • 5
  • 1