views:

86

answers:

4

Is there a way to tell if a user on my website has left (i.e. connection dropped, navigated away etc.) in real time?

I am building a RoR website and want to initiate an event as soon as a user leaves my site for whatever reason (e.g. connection, navigating away from domain etc.)

Thanks in advance for any help.

A: 

All I can think of is JavaScript onunload event in your body tag... I don't know how viable that is, but in theory you could have that use an AJAX call to send information about an impending disconnect.

Of course, if the browser process is just killed that won't work.

And I'm not sure if Rails has any unique magic that does this same thing (except better).

Platinum Azure
This won't work if the user loses his connection.
SLaks
@SLaks: True. I guess your approach of proactively sending heartbeat info is better.
Platinum Azure
+4  A: 

No, there isn't.

The best you can do is send an AJAX request every X seconds (perhaps only if the user moves the mouse). If the server doesn't receive any requests for 2X seconds, assume that the user left.

SLaks
+2  A: 

Nope.

Http = connectionless

P.Brian.Mackey
A: 

You can do some request in this function:

$(window).bind('beforeunload', function(){ 
  // there
});

Send some Ajax or something to tell the server that this user is leaving the page, but this is not a good idea. In Google analytics and in other statistic services you already can see how long the user stays in your page.

Gacha