views:

66

answers:

5

Hello,

we have an web-application built in flash (it's actually just getting built :D) where is very important to be notified, when user closes his window.

Since it's in flash, we do not worry about Javascript, we do not support non-javascript users.

What is the safest (meaning it's 100% sure it gets called) X-browser way to call php script to close session, make some db changes, etc.?

Thank you

A: 

The onbeforeunload and/or onunload events are probably what you are looking for. You can probably fire off an ajax call there but it could be possible that it gets interrupted when the page is actually onloaded.

If detecting users leaving via a link is enough, simply fire off an ajax request in $('a[href]').click(...);

ThiefMaster
If you initiate an asynchronous ajax call in `onunload`, it's extremely unlikely it will get processed at all. You'd have to make it synchronous, which is ugly. (But I've done it, for intranet apps, and it was barely noticeable. An inTERnet app would probably have a more noticeable delay.)
T.J. Crowder
synchronous code?
Adam Kiss
onbeforeunload and onunload have a limited time window in which they can run - if they don't finish in that window, they get terminated; as such, they are unreliable.
Piskvor
+2  A: 

There is no method which is 100% sure to work. You can't get a signal form the client if there is a network problem, power cut, etc.

Periodically run a clean up script (based on time, not activity) that performs all the deletions etc for sessions which have had no activity in X minutes.

David Dorward
we deal more in seconds, it would be probably too much to call clean-up script every five seconds?
Adam Kiss
You would need a server fast enough to process the entire database in under 5 seconds when under maximum load. You would also need every user to have a sufficiently fast and stable Internet connection to send a heart beat every less-than-five-seconds. Do you really want the system to treat them as "Gone away" if their connection stalls for 10 seconds?
David Dorward
Well, we're talking about something like IP telephony thru flash, so we'll probably stick with red5 checking whether client is still streaming/online.
Adam Kiss
A: 

There is not way to ensure that. The closest you can get is doing something in the onunload or beforeunload events.

RoToRa
A: 

When using jQuery you can use the example posted here http://stackoverflow.com/questions/653976/call-url-before-closing-of-browser-window

The basic idea of this to make an ajax request when the window/tab is being closed.

Tim
A: 

There is no 100%, sure-fire way to detect this. It may be possible (others can perhaps elaborate on this) to perform some AJAX call on the onunload event, which you can use to perform some clean-up, but you cannot rely on this. Browsers may crash, or exhibit unsuspected behavior. Or users may simply not close the browser for a very long time.

Daan