Shrima Mukherjee
Shrima Mukherjee

Reputation: 1

Javascript time track

my requirement is 15 minutes after visiting the site, user will navigate to registration page. And I need to track the page even after open that page again, user will navigate to registration page.

As the requirement I think it will be possible with cookie, but I need to count the time of visiting the site. When site visiting minutes reach to 15 js will fire a function and there I can set the cookie and redirect.

Can any one please help me to track the site visiting minutes by js?

Upvotes: 0

Views: 239

Answers (1)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76413

Although I agree with epoch, it can be done using localStorage:

(function (timer)
{
    var now = new Date();
    var redirect = function()
    {
        location.href = 'register url';
    }
    if (!localStorage.getItem('registrationMinutes'))
    {
        localStorage.setItem('registrationMinutes',(+now)+60000*15);//time +15 minutes
    }
    if (localStorage.registrationMinutes <= +now)
    {//on page load, check if 15 mins are up
        return redirect();
    }
    timer = setTimeout(redirect,localStorage.registrationMinutes - now);//call function when time is up
})();

Just include this little function on all pages. You might want to set a cookie like userIsRegistered, and not set the timeout when the client has already been registered.
Just know that this code will be sent to the client, and he or she is still free to disable cookies, JS,... and, I think, localStorage isn't supported by older IE browsers (there's a surprise!)
If all this is a bit much, here's a simple copy-paste snippet:

(function (url,now,timer)
{
    var redirect = function()
    {
        location.href = url;
    }
    if (!localStorage.getItem('registrationMinutes'))
    {
        localStorage.setItem('registrationMinutes',(+now)+60000*15);//time +15 minutes
    }
    if (localStorage.registrationMinutes <= +now)
    {//on page load, check if 15 mins are up
        return redirect();
    }
    timer = setTimeout(redirect,localStorage.registrationMinutes - now);//call function when time is up
})('redirectUrl',new Date());

just replace the 'redirectUrl' string with your url, and it should work just fine. There is also no need to change variable names: it's all contained in this anonymous function's scope, so there is no conflict with variables declared in the parent scope.

Upvotes: 1

Related Questions