Garrett R
Garrett R

Reputation: 531

How to tell if someone has left

I was wondering how I could check if someone has left the site/page and perform an action after they left. I was reading on here and I found this:

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.

That's what I had planned for before but how could you make the server do something (in my case it's to remove them from the DB) if they stop sending the request? An example I can think of is how on Facebook when you go to the site you tell them you're here and online which marks you as online in chat but when you leave it marks you as offline. How is that possible?

Edit: After a while of using cron jobs I found out that web hosting sites don't like running cron jobs often enough to generate a "live" feelings on your site. So instead I found node.js and it works a 1000x better and is much simpler. I'd recommend anyone with the same issue to use it, it's very cheap to buy hosting for and it's simple to learn, if you know Javascript you can build in it no problem. Just be sure to know how Async works.

Upvotes: 3

Views: 821

Answers (3)

user557846
user557846

Reputation:

A not uncommon approach is to run a cron job periodically that checks the list of users, and does XYZ if they have been inactive for X minutes.

Upvotes: 2

chris
chris

Reputation: 36947

The only method I ever remember in my time developing is one that's not 100% reliable as a number of factors can actually and most likely cause it to either misfired, or not even run fully. Up to and including someone disabling JavaScript. Which grant it isn't highly likely with the way websites of today are put together. But people have the option to turn it off, and then people who are acting maliciously tend to have it off as well.

Anyway, the method I have read about but never put much stock in is, the onunload() event. That you tie into something like the <body> tag.

Example:

<body onunload="myFunction()">

Where myFunction() is a bit of JavaScript to do whatever it is your seeking to have done.

Again not superbly reliable for many reasons, but I think in all it's the best you have with almost all client side languages.

Upvotes: 1

JCOC611
JCOC611

Reputation: 19729

Facebook uses the XMPP protocol via the Jabber service to have a constant or real-time connection with the user. However, implementing one isn't an easy task at all. The most simple solution would be, as mentioned in the comments, to have the client make AJAX requests to the server every several seconds, so that the server may check whether the user is still viewing the site or not.

You might want to check out my question, which might be related to yours.

Upvotes: 1

Related Questions