views:

4016

answers:

3

What is the best way to detect if a user leaves a web page?

The onUnload javascript method doesn't work every time (the HTTP request takes longer than the time required to terminate the browser).

Creating will probably be blocked by current browsers.

I'm also using Silverlight, so Silverlight solutions are welcome.

+4  A: 

One (slightly hacky) way to do it is replace and links that lead away from your site with an AJAX call to the server-side, indicating the user is leaving, then use that same javascript block to take the user to the external site they've requested.

Of course this won't work if the user simply closes the browser window or types in a new URL.

To get around that, you'd potentially need to use Javascript's setTimeout() on the page, making an AJAX call every few seconds (depending on how quickly you want to know if the user has left).

Steve M
If you use the report home approach, there's no need to modify every link in the page.
Vinko Vrsalovic
+18  A: 

try onBeforeUnload.

with onbeforeunload you can even ask back if the user really wnats to leave.

see this demo

alternatively, you can send out an ajax request when he leaves.

Andreas Petersson
Thanks for the tip! Thanks to you I was able to achieve a new JS magic trick :)
Gilles
Nice ! I was never sure if that was a "rude" thing for a web page or app to do, but I guess for ajaxey apps, it makes good sense.
Michael Neale
It'd be nice for the user if you tracked if the form changed and only prompt if it did - so it's not annoying.
adam0101
+2  A: 

In Silverlight there is a event in App.xaml.cs Exit. The default handler for it Application_Exit. It fires when you leave the application.

Tanmoy