Tim
Tim

Reputation: 47

Measure time a user stays in a webpage and display it for the admin (Python - Django)

I have a website built in django. All pages are static. Now I'm trying to measure time each user spends in each page and display it in a table. Currently I'm working on an idea I got in another similar topic as in the link: How to measure a time spent on a page?

Firstly I have placed this in the header of the page which imports the TimeMe.js library and initializes it. This captures the time a user spends on the webpage:

<script type="text/javascript">
            TimeMe.setIdleDurationInSeconds(15);
            TimeMe.setCurrentPageName("my-home-page");
            TimeMe.initialize();
            window.onload = function(){
                setInterval(function(){
                    var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds();
                    document.getElementById('timeInSeconds').textContent = timeSpentOnPage.toFixed(2);
                }, 25);
            }
            </script>

Then I have the following for sending the measured time to the server (I'm working locally, in my laptop):

window.onbeforeunload = function (event) {
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("POST","http://127.0.0.1:8000",false);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds();
    xmlhttp.send(timeSpentOnPage);
};

I'm a beginner in Javascript and I don't understand where should I use the second piece of code to post data to the server in order to display them in a view. Is the format of the code correct?

Thank you

Upvotes: 0

Views: 1610

Answers (1)

C14L
C14L

Reputation: 12548

Sending the data onunload may or may not work.

Another way would be to ping your server every x seconds, so you know that the use has the page still open.

setInterval(function () {
    xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", "http://127.0.0.1:8000",false);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send();
}, 15);

The ping sends the session cookie along with it, so you know which user it is and can count the time on the server.

However, if you just want to know how much time each user spends on your pages, its probably easier to add Google Analytics (or a self-hosted alternative like Piwik) to your site and have the metrics collected and presented in a tested and reliable way.

Upvotes: 1

Related Questions