0
<input type="button" value="Start Timer" onclick="timeTracker._recordStartTime();"/>  
<input type="button" value="Stop Timer" onclick="timeTracker._recordEndTime();"/>  
<input type="button" value="Track!" onclick="timeTracker._track(pageTracker, Category, 'Manual Test');"/>

This is an internal event tracking code(using the action on click) and I would like to implement something similar like this that the "timeTracker._recordStartTime() starts when the page opened(loads) then "timeTracker._recordEndTime()" and "timeTracker._track(pageTracker, category, 'Manual Test') called when the user leaves the page(normally navigating away to another page).

my goal is to record the time spent on page as event and put in category with other events like on click JavaScript events.

How can I do this ?

0

1 Answer 1

1

You can use the window.performance.timing Object to calculate the time on page. https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/NavigationTiming/Overview.html#processing-model

First you should bind an onunload event handler to your body, like:

<body onunload="trackPageTime(event);">
...
</body>

Then, implement your function to calculate the time difference and push to the _gaq Object.

<script type="text/javascript">
function trackPageTime(e){
    var onPageSeconds = ((new Date()).getTime() - window.performance.timing.domInteractive) / 1000;
    var gaps = [1,2,3,4,5,10,20,30,60,120,300,600];
    for(var i=0;onPageSeconds>gaps[i] && i<gaps.length;i++);
    _gaq.push(['_trackEvent', 'Time on Page', (document.location.pathname+document.location.search).toString(), gaps[i].toString()]); 
}
</script>

You could use different properties of the "timing" Object to calculate Page On Time, such as the responseEnd (some may say this is more correct), however, i've found that the domInteractive property would give me more approximate results.

Not the answer you're looking for? Browse other questions tagged or ask your own question.