MariusNV
MariusNV

Reputation: 320

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;
setInterval(function(){
    ++time_spent;
    $('#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 (https://github.com/js-cookie/js-cookie) in the following manner:

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

But the counted_time variable is always 'undefined' whatever I've tried.
I would really apreciate any guidance I can get in order to solve this little issue.

Upvotes: 1

Views: 1198

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

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

Upvotes: 2

Related Questions