views:

346

answers:

2

Two years ago I had a need to trap the closing of a web browser as a javascript event for a web app. At the time I found there was no way doing this that worked for all browsers. IE had an event that I could used, but it was IE specific. I looked into other work arounds, like a heart beat sort of ping to the server, but I didn't like any of them at the time.

Is there anyway currently to trap the closing of a web browser now? Thanks!

+2  A: 

onunload works in IE and Firefox.

17 of 26
This method is fine as long as you do not intend to cancel the close. If you do, you'll need onbeforeunload.
Richard Szalay
+7  A: 

You can use the

window.onbeforeunload

javascript event to do this, though this will trap more than just closing the browser. This event will also get fired each time someone tries to navigate to another page, refresh the current page, etc. It's handy if you're trying to do something like warn people of unsaved changes before they leave the current page.

Jesse Taber
Event names are all lower case in the HTML DOM. Recommend you change to "window.onbeforeunload".
Richard Szalay
With this method, won't some piece of information have to be included in the query string? Otherwise how would you keep the user valid? I think this is why I did not use an unload type event when I originally looked into doing this.
Flynn81
I don't follow. Using this event shouldn't interfere with (or be used for) any kind of session/authentication management. Could you elaborate a bit on your situation (either in the comment or in the question itself)?
Jesse Taber
Richard: good call, changed.
Jesse Taber
This usually doesn't work in Opera: http://www.opera.com/support/kb/view/827/
Knio