user1537415
user1537415

Reputation:

Count how many times user has loaded a page on my site?

I'm wondering if I can count the times user loads pages on my site, with JavaScript. Probably like this?

var pageloads = 1;
$(document).ready(function(){
var pageloads =++
});

But where would I store it? In a cookie?

Upvotes: 1

Views: 9815

Answers (5)

daveyfaherty
daveyfaherty

Reputation: 4613

It's not possible - edit: to track an actual user.

You can only ever track a particular instance of a browser using cookies.

There is no such thing as tracking a "user" using javascript alone. You can reliably count things like user logins though.

Upvotes: -1

adeneo
adeneo

Reputation: 318302

If older browsers like IE7 and below are'nt an issue, you can use local storage:

$(function(){
     var loaded = parseInt(localStorage.getItem('loaded'), 10),
         loaded_numb = loaded?loaded+1:1;
     localStorage.setItem('loaded', loaded_numb);

     $('body').append('<p>This page was loaded by you '+loaded_numb+' times !');
});

FIDDLE

Upvotes: 4

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

Reputation: 67131

Easier to just do it with cookies (especially since there's no reason to totally block out IE7 and lower)

var numLoads = parseInt(getCookie('pageLoads'), 10);

if (isNaN(numLoads) || numLoads <= 0) { setCookie('pageLoads', 1); }
else { setCookie('pageLoads', numLoads + 1); }

console.log(getCookie('pageLoads'));

getCookie/setCookie simple get/set functions (can be found in the jsFiddle)

jsFiddle Demo

Upvotes: 3

Explosion Pills
Explosion Pills

Reputation: 191779

Why would you want to do this with Javascript? Whatever server you're using should have access logs that store all requests, IPs that make the requests, and a lot more. There are even free log file analyzers like awstats and Google Analytics. You should do this on the server side, not the client side.

If you really want to store it with JavaScript, then your only options are a cookie and LocalStorage -- both of those are quite transient.

Upvotes: 0

Tom G
Tom G

Reputation: 3660

You could store it in a database. If you are looking for monitoring the traffic on your web page you should look at Google Analytics http://www.google.com/analytics/.

They show you how many people visited your site, whether they are new or returning, the path they took through your site, bounce rate etc. Best part is it's free.

Upvotes: 0

Related Questions