0

I want to find the time a user spend on an article page.

I have page which shows list of an articles , when you click any article from that page it will show you the content of that article.

For now i have the following code for the article route

@app.route("/post/<post_id>")
def post(post_id):
post = mongo.db.articles
sp = post.find_one({'_id': ObjectId(post_id)})
##################
userhistory = mongo.db.userhistory 
history = {'id' :ObjectId(post_id),'title':sp['Heading'],'User':current_user.user_json['email'],'DateTime':datetime.now()}
userhistory.insert(history)
############################################
#sp = post.find_one({'_id':post_id})
return render_template('post.html', title=post.title, post=sp)

I want to calculate the time a user spends on that specific article and add it to MongoDB collection(user history). So when a user has finished reading the article and clicks back on the browser it should calculate the time spent.

Please Help

ShivaGaire
  • 2,283
  • 1
  • 20
  • 31
adnan
  • 504
  • 1
  • 4
  • 21

1 Answers1

3

This is something that you should calculate on client side (e.g. javascript) and not on the server side, because there is no way to ensure that the client will send another request to your server when he finished reading it (by navigating to another page, closing the browser, etc...)

There is an easy solution: Use some already existing analysis-tool like Google Analytics or Matomo (Open Source). They will provide you with statistics how long a user spend on a specific page.

If you want to implement it yourself here is a starting point: How to measure a time spent on a page?

Frieder
  • 1,208
  • 16
  • 25
  • Does these tools working on the site running on my machine only (Localhost) – adnan Jan 04 '19 at 15:25
  • Google Analytics needs an working internet connection to load the scripts from the google servers, therefore will not work on intranet only applications. Matomo will work on your local server, but you need additional software (working php + sql server). But also keep in mind that they are both pretty big analysis tools and it may be an overkill to use them. On the other hand they will provide detailed statistics about the usage of your website, not only the time spent on a page. – Frieder Jan 04 '19 at 15:30