Search code examples
javascriptweb-analyticstime-tracking

How do I get real-time "timeonsite" parameter when integrating with timeonsitetracker.js API in web pages?


I integrated the JS timeonsite library timeonsitetracker.js in web page as given in document,

<script type="text/javascript">
var Tos;
(function(d, s, id, file) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s);
    js.id = id;
    js.onload = function() {
        var config = {
            trackBy: 'seconds',
            developerMode: true
        };
        if(TimeOnSiteTracker) {
            Tos = new TimeOnSiteTracker(config);
        }
    };
    js.src = file;fjs.parentNode.insertBefore(js, fjs);
 } (document, 'script', 'TimeOnSiteTracker', '//cdn.jsdelivr.net/gh/saleemkce/[email protected]/timeonsitetracker.min.js'));
</script>

After calling the Tos object,

Tos.getTimeOnPage();

{
    TOSId: 13650383319214852
    TOSSessionKey: "6606159448467693493359"
    TOSUserId: "anonymous"
    URL: "https://localhost/index.html"
    currentTime: "2020-07-11 16:25:17.908"
    entryTime: "2020-07-11 16:24:36.911"
    timeOnPage: 41
    timeOnPageByDuration: "0d 00h 00m 41s"
    timeOnPageTrackedBy: "second"
    timeOnSite: 0
    timeOnSiteByDuration: "0d 00h 00m 00s"
    title: "real-time demo"
    trackingType: "tos"
}

On calling the Tos.getTimeOnPage() API, I see the "timeOnSite" always "0" but timeOnPage updates periodically. But on refreshing the page, I get the updated timeOnPage, timeOnSite in DB saved automatically by tracker. Is there a way to get the real-time "timeonsite" param on page without refreshing the whole page as given in demo page?


Solution

  • In demo page, what they are doing is basically:

    $(document).ready(function() {
       
        setInterval(function() {
        
        $('#timeOnSiteDuration').html(Tos.secondToDuration((Tos.getTimeOnPage()).timeOnSite + (Tos.getTimeOnPage()).timeOnPage));
                        
       }, 1000);
    
    }
    

    They set an interval of 1sec in document.ready to update the 'div' that has an id='timeOnSiteDuration' with the time on site calculation.

    I think a solution that you can do is something like that: using setInterval and calculating the time on site with:

    Tos.secondToDuration((Tos.getTimeOnPage()).timeOnSite + (Tos.getTimeOnPage()).timeOnPage)
    

    You can set this calc to a variable or do like the demo page, show it direct in html.