views:

2395

answers:

5

Is there any way of knowing if the user closes a tab in a web browser? Specifically IE7, but also FireFox and others as well. I would like to be able to handle this situation from our asp code if the current tab containing our web site closes.

+1  A: 

Does document.unload not do it if you?

document.unload is client-side so you'd have to go a step further to be able to handle it server-side (in your asp code) and maybe fire off an AJAX request from the document unload event handler?
kristian
Would an Asynchronous call work? I mean... the tab is being killed, surely it's better to be synchronous and to lock it in some way.
You don't need a synchronous request because the page doesn't care about the response (in fact it will probably be closed by the time a response is returned).
kristian
+1  A: 

Attach an "onbeforeunload" event. It can execute code just before the browser/tab closes.

Eran Galperin
Thanks guys. I'm passing these details on to our asp developer and will vote for the answers based on her findings.
_J_
Note that onbeforeunload doesn't work in Opera. onunload works in Opera though, but only when navigating away from the page by clicking a link for example. onunload won't fire in Opera if you close the tab or reload the page.
Shadow2531
A: 

If you need to know when the page is closed at the server side, your best bet is to ping the server periodically from the page (via XMLHttpRequest, for example). When pinging stops, the page is closed. This will also work if the browser crashed, was terminated or the computer was turned off.

Nickolay
A: 

As Eran Galperin suggested, use onbeforeunload. Particularly, return a string, and that string will be included in a confirmation dialog which will allow the user to choose whether or not to leave the page. Each browser includes some text before and after the string you return, so you should test in different browsers to see what a user would be presented with.

eyelidlessness
A: 

Cann't we use cookies?

Sandy