Web API Core | ComponentOne
Services / Visitor API / Browser Fingerprinting
In This Topic
    Browser Fingerprinting
    In This Topic

    Browser fingerprinting is the capability of websites to use the information provided by browsers to identify visitors and track their online behavior. It is an accurate and powerful method used by the websites to collect information about your browser type and version, time zone, operating system, active plug-ins, language, and various other active settings. With this, whenever you connect to the internet using any device, such as laptop, smartphone or PC, the device hands over some specific data to the receiving server about the websites you visit.

    Visitor API supports browser fingerprinting and collects information from the browser to identify visitors using the following:

    The following example generates a unique visitor id and displays visit history of that id. In this example, the handleGetVisitorDataAsync function is used for handling Visitor data received from the API by starting the timer to get the visit time for the page and saving sessions information for the Visitor at client for future using the saveVisitorData function by generating key with time along with visitorID and saving it in local storage. In addition, saveVisitorData function saves the visitors data from the unique id which is used to save the browsing history. Moreover, in this example, we are creating Google Maps and setting the location of visitor using the createMap function and fetching the history from local storage using the bindHistories function for displaying the visit histories of a visitor.

    BrowserFingerprinting.cshtml
    Copy Code
    @using Microsoft.Extensions.Configuration
    @inject IConfiguration Configuration
    
    @section Styles{
        <style>
            #map {
                height: 450px;
                width: 100%;
            }
    
            #histories-container {
                max-height: 249px;
                overflow-y: auto;
            }
        </style>
    }
    
    <h3>Your Unique Visitor Id</h3>
    
    @section Summary{
        @Html.Raw(Visitor.Description)
    }
    
    <div>
        <div class="col-md-6">
            <table class="table">
                <tbody id="current">
                    <tr>
                        <td id="visits"><span id="visitorId"></span></td>
                    </tr>
                    <tr>
                        <td id="timer"></td>
                    </tr>
                    <tr>
                        <td id="totalVisitedTime"></td>
                    </tr>
    
                </tbody>
            </table>
    
            <div class="h4"<label>Visit Histories</label></div>
            <div id="histories-container">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Visitor Id)</th>
                            <th>Visit Date)</th>
                        </tr>
                    </thead>
                    <tbody id="histories">
                    </tbody>
                </table>
            </div>
    
        </div>
        <div class="col-md-6">
            <div id="map"></div>
        </div>
    </div>
    
    <script src="@(Configuration["WebAPIService"])api/visitor/visitor-client.min.js"></script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=@(Configuration["GoogleMapApiKey"])"></script>
    <script>
        window.onload = function () {
    
            if (!String.prototype.format) {
                String.prototype.format = function () {
                    var args = arguments;
                    return this.replace(/{(\d+)}/g, function (match, number) {
                        return typeof args[number] != 'undefined'
                                ? args[number]
                                : match;
                    });
                };
            }
    
            // get Visitor Data from the API
            window.visitor.getDataAsync(handleGetVisitorDataAsync);
            // Create Google Maps and set the location of visitor (user)
            function createMap(geo) {
                // extract GeoLocation from the VisitorData
                var position = { lat: geo.latitude, lng: geo.longitude };
                //create map
                var map = new google.maps.Map(document.getElementById('map'), { zoom: 14, center: position });
                // set user current location 
                var marker = new google.maps.Marker({ position: position, map: map });
            }
    
            // handle Visitor data recieved from the API
            function handleGetVisitorDataAsync(data) {
                // Set for how long the current page is opened
                startTimer();
                // save Visitor information on localstorage
                saveVisitorData(data.visitorId, data.session);
                // set VisitorID in DOM
                var visitorIdElement = document.getElementById('visitorId');
                visitorIdElement.innerHTML = data.visitorId;
                // Create Map with current location
                createMap(data.geo);
                // show all saved session infromation from localstorage
                bindHistories(data.visitorId);
            }
    
            function setTotalVisitedTime(time) {
                document.getElementById('totalVisitedTime').innerHTML = '@Html.Raw(Visitor.Template_Total_Visits_Time)'.format(time);
            }
            // save Sessions information for the Visitor at Client for future 
            function saveVisitorData(visitorId, session) {
                // generate key with time along with visitorID
                var key = genKey(visitorId);            
                var pureItem = {
                    visitorId: visitorId,
                    start: session.start
                };
                // save in localstorage with key
                localStorage.setItem(key, JSON.stringify(pureItem));
                // generate the key with datetime and visitorID information
                function genKey(visitorId) {
                    return 'visitorId-' + visitorId + '-' + new Date().toISOString();
                }
            }
            // fetch the history from localstorage and show in DOM
            function bindHistories(visitorId) {
                var source = [];
                for (var key in localStorage) {
                    if (matched(key)) {
                        source.push(JSON.parse(localStorage.getItem(key)));
                    }
                }
                //show history in table
                renderHistories();
                //show number of visits
                setTotalVisitedTime(source.length);
                // show history in DOM table
                function renderHistories() {
                    var table = document.getElementById("histories");
    
                    var sortedSource = source.sort(function (a, b) {
                        a = new Date(a.start);
                        b = new Date(b.start);
                        return a > b ? -1 : a < b ? 1 : 0;
                    });
    
                    for (var i = 0; i < sortedSource.length; i++) {
                        renderRow(i, sortedSource[i]);
                    }
    
                    function renderRow(index, visitorHistory) {
                        var row = table.insertRow(index);
    
                        renderCell(0, visitorHistory.visitorId);
                        renderCell(1, visitorHistory.start);
    
                        function renderCell(cellIndex, text) {
                            var cell = row.insertCell(cellIndex);
                            cell.innerHTML = text;
                        }
                    }
                }
                // find if key matched
                function matched(key) {
                    return key.indexOf('visitorId-' + visitorId) > -1;
                }
            }
    
            var browsingTimeTemplate = '@Html.Raw(Visitor.Template_Browsing_Time)';
            console.log(browsingTimeTemplate)
            // start timer to get visit time for page
            function startTimer() {
                var now = 1;
                setTimerLabel();
    
                window.setInterval(function  () {
                    now++;
                    setTimerLabel();
                }, 1000);
    
                function setTimerLabel()
                {
                    document.getElementById('timer').innerHTML = browsingTimeTemplate + ' ' + now + '(s)';
                }
            }
        }}
    </script>