简体   繁体   中英

Report the time spent on a page to the server

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.

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.

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 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.

您也可以尝试PiWik ,它为您提供有关您网站访问者的类似统计信息。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM