Calculate time online with JavaScript / jQuery

3

I need to develop a code where I do not have access to back-end languages, I need to do a function that calculates how long a user is online on the page and save this time in localStorage in>, I thought I'd use a setInterval every 1 second to update the time that it's online . And then update the value in storage, however I do not know how to work with Javascript / jQuery time. How could I do that?

    
asked by anonymous 05.04.2014 / 04:29

1 answer

2

Here's a suggestion:

Use the domready event to register the milliseconds (timestamp) when the page loads. Then use the beforeunload event to run code just before the page closes. You can also play with focus in case you want to know when the page is in focus, or you are not viewing this page (without focus).

code:

var aberturaPagina;
$(window).ready(function () {
    aberturaPagina = new Date().getTime();
});
$(window).on('beforeunload', function () {
    var fechoPagina = new Date().getTime();
    var tempoAberto = (fechoPagina - aberturaPagina) / 1000;

    // faxer qualquer coisa antes de fechar

});

Example

In my example, a new window opens to show the seconds. Unlock pop-ups to see the result. This code is an example. You may want to make an AJAX call to register in the database.

    
05.04.2014 / 08:08