How is it possible to identify that the browser's close button was clicked?
Browsers do not have a close event so you can't really tell when the user has closed their browser, there are some potential workarounds in This thread
If you let us know what you are trying to achieve, there may be an alternative way
would this :
$(window).unload( function () { alert("Bye now!"); } );
help you ?
It is in jQuery though.
you should check the link given by Demoli though, it has further information about this particular method ( and its downside ).
edit : added link.
From the JavaScript Event Reference, the closest match appears to be the OnUnload event. However, this also catches navigation away from the page (and thus you don't want the functions to run if the user actually clicks on a link.)
There is no guarantee that the server will receive the message that the browser window is closed. For example, the older method that involved creating a small pop-up window would be blocked by most modern browsers. Using AJAX might work, but a browser window may close before it attempts to connect.
There is usually an event which fires when the user leaves the page (unload?) - this may be browser specific.
There is also a property, window.closed, which is set on the window object after its associated window is closed. This is typically used when you have a reference to a popup window.
I'm not sure whether the unload event would be fired before or after the "closed" property is set - you'll have to experiment.
It may be that you can't distinguish between a closed window and a browser which has gone to another site.
you could setup an ajax call that periodically polls your server every few seconds to every few minutes (depending on your wanted time precision) and track the last hit time server side. not completely accurate (eg. network issues could cause a false positive), but may be an option depending on your requirements.
you should use onbeforeunload
, not onunload
. IE 7 (and perhaps other browsers) are not 100% reliable when it comes to firing the unload
event, but it seems to always fire the beforeunload
event.
for example, window.onbeforeunload=function(){}
or, if you are using prototype.js: Event.observe(window, 'beforeunload', function(){});
This is a hack but it seems to work for me. It might be IE specific as well. I code for an IE only environment.
<body onunload="if(self.screenTop>9000){unloadFunction();}">
Edited to add that my unloadFunction opens a popup window that kills the user's session. You can't do anything on the page that was closed itself. 'cause it's closed already! ;)