views:

125

answers:

4

Is it possible to report the time spend on a page back to server when the visitor leaves the page by closing the tab or the browser? Using Javascript.

And it will work on Firefox, Google Chrome, Safari, Opera, and IE8 (IE7 and 6 are not important).

But it will work in any case; even while the browser is closing, or it is typed another address.

+4  A: 

You can try windows.onbeforeunload but there is no guarantee that it will work in all cases.

Anyway I suggest you use google analytics which has that feature among many others (I doubt you can do better than google!). It's free.

Andreas Bonini
+1  A: 

You could also try PiWik which offers you similar statistics about the visitor of you website.

Hippo
+1  A: 

If you want to implement this yourself, you need to decide when to get the start time--you can put a script tag at the top of the page, which may execute before the content has rendered, on the onload event, which will wait until all images and scripts have loaded, or something like the the JQuery ready event, which occurs when the DOM is ready, but doesn't wait for resources to load. At this point, you'd want to record a start time:

<script>var startTime = new Date().getTime();</script>

Then you can listen for the onunload or onbeforeunload event and use an image to send a GET request with the info:

<script>
  window.onunload = function() {
    var i = new Image();
    var timeSpentMilliseconds = new Date().getTime() - startTime;
    i.src = '/pagetime?timespent=' + timeSpentMilliseconds;
  }
</script>

You'll have to do some testing to see whether the requests are always sent--I'm sure sometimes the browser closes or the tab switches before they finish firing.

Annie
+1  A: 

Hi. Why not use Google Analytics directly? Besides what you want, it provides much more data for your analytics. And, it is free. Regards, freezea.

freezea
Google Analytics do not provide IP based information. I'll make this code for my coisin's web site, and for fun for myself. He is has just got system-network certifcates from microsoft exam. and we (i actually) made an web site for him. he is waching every visit to his site (1 per 3 days) wheter it is from a corporotian IP or not, which corporation. and we want to learn how much time a "worker seeker" spends in his website. and and and i'm statistcs student, i might use it for statistical purposes.
ilhan