Friday, 14 January 2022

Can I use sendBeacon to save session duration metric real-time in timeonsite JS tracker including IOS devices?

I have integrated the timeonsite JS library to track users time spent information in my MySql DB. I'm using following code to achieve the same. But, the data is not getting stored in IOS devices like iphone or ipad but works in all other browsers like Chrome, Edge, Opera, Firefox etc. including Android chrome and firefox.

<head> 
<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',
                callback: function(data) {
                    console.log(data);
                    // give your endpoint URL server-side URL that is going to handle your TOS data which is of POST method. Eg. PHP, nodejs or python URL which saves this data to your DB

                    var endPointUrl = 'http://localhost:4500/tos'; // replace with your endpoint URL

                    if (data && data.trackingType) {
                        if (data.trackingType == 'tos') {
                            if (Tos.verifyData(data) != 'valid') {
                                console.log('Data abolished!');
                                return; 
                            }
                        }
                        
                        // make use of sendBeacon if this API is supported by your browser. sendBeacon is experimental technology; it may not work well
                        if (navigator && typeof navigator.sendBeacon === 'function') {
                            var blob = new Blob([JSON.stringify(data)], {type : 'application/json'});
                            navigator.sendBeacon(endPointUrl, blob);
                        }
                        
                    }     
                }
            };

            if (TimeOnSiteTracker) {
                Tos = new TimeOnSiteTracker(config);
            }
        };
        js.src = file;fjs.parentNode.insertBefore(js, fjs);
    } (document, 'script', 'TimeOnSiteTracker', 'https://cdnjs.cloudflare.com/ajax/libs/timeonsite/1.2.0/timeonsitetracker.js'));
</script> 
</head>

What's the reason for this issue and how to get it resolved? Thanks in advance.



from Can I use sendBeacon to save session duration metric real-time in timeonsite JS tracker including IOS devices?

No comments:

Post a Comment