MariusNV MariusNV - 1 year ago 120
jQuery Question

How to store a variable inside a JavaScript session cookie?

I want to keep track of how many seconds a user spend on my project website on all of his pages and for doing this I want to use JavaScript session cookies.

This is because I will host it using Github Pages where I have no access to PHP and also because I want to try working with JS cookies (It's the first time I am doing this).

To count the seconds I am using the followings:

var time_spent = 0;
$('#counter_container span').html(time_spent);
}, 1000);

The above code works where the counter is but as expected is reseting every time I change the page.

I've tried using a js-cookie library ( in the following manner:

Cookies.set('time_spent', time_spent);
var counted_time = Cookies.get('time_spent');

But the
variable is always 'undefined' whatever I've tried.

I would really apreciate any guidance I can get in order to solve this little issue.

Answer Source

I wouldn't use a timer for this. Instead try setting a timestamp when the user enters the page, and then onbeforeunload get the duration and add it to the value stored in the cookie. Something like this:

var load = new Date();

window.onbeforeunload = function() {
    var leave = new Date();
    var duration = leave.getTime() - load.getTime() / 1000;
    var counted_time = parseFloat(Cookies.get('time_spent')) || 0;
    Cookies.set('time_spent', counted_time + duration);

Working example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download