0

I'm trying to tell the difference between when a user is leaving a page on my website for a different website (or closing the browser), or for a different page on my website. onbeforeload() doesn't make this distinction. Is there another way to make this possible with javascript? I have a script I want to fire only if the user is leaving permanently, and not simply going from page A to page B on my website.

user2250471
  • 1,002
  • 3
  • 10
  • 23
  • Google Analytics gives you this information right out of the box. – Luke Peterson Jun 21 '14 at 21:48
  • 1
    You can use pushState to detect users leaving the website to your website and then deduce that users who don't show up there are leaving or have old browsers. – Benjamin Gruenbaum Jun 21 '14 at 21:49
  • I need to be able to update values in my database when the user leaves the site completely, for functionality other than visitor tracking. @LukePeterson – user2250471 Jun 21 '14 at 21:49

1 Answers1

0

The common model for doing this (or at least I think it is common) is to give the user a unique id, which you save in a session variable or a cookie and you make an entry into a database table corresponding to that ID. Each the time the user visits another site this ID is sent to the server (Either by a script using AJAX or if you saved the ID into a session variable you can check just on the server) and save the current time into a database.

Then you need to have a background program running which then, for example checks every minute if the user was inactive for more than, let's say 7 minutes. If he was you can be relatively sure he has left.

If it is really necessary to be up-to-date you can low down that to span to for instance 1 minute and send an ajax call every 30 seconds to update the database timestamp.

idmean
  • 14,540
  • 9
  • 54
  • 83