Capture Script Opening Time

1

Hello, everyone.

I'm trying to create a project, whose function is to identify how long the page is open (ie if it's been 1 or 2 minutes open). When it is closed, save the time information in the database.

However, I'm a denial with javascript, jquery, and the like. Here is sample code:

<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script><script>varaberturaPagina;$(window).ready(function(){aberturaPagina=newDate().getTime();});$(window).on('beforeunload',function(){varfechoPagina=newDate().getTime();vartempoAberto=(fechoPagina-aberturaPagina)/1000;$.ajax({type:"POST",
      url : "http://url.exmplo.com.br/codigo_db.php?id=1&tempo=" + tempoAberto,
        sucess : function(html){
        $('.div').html(html);
      }
    })
  });
</script>

When you run the page, nothing happens!

I've set up this frankenstein with codes from some forums, can anyone help me fix it?

    
asked by anonymous 18.02.2016 / 22:29

1 answer

3

Browsers ignore asynchronous requests initiated in the unload event. There are at least two ways around this: make a synchronous request or use the navigator.sendBacon API. The latter is not supported in IE 11 but has the advantage of being asynchronous and therefore does not block the browser during the duration of the query.

Example with synchronous request:

var aberturaPagina;

window.addEventListener('load', function () {
  aberturaPagina = new Date().getTime();
});

window.addEventListener('unload', function () {
  var fechoPagina = new Date().getTime();
  var tempoAberto = (fechoPagina - aberturaPagina) / 1000;
  var client = new XMLHttpRequest();
  client.open('POST', 'http://requestb.in/1a4i8zc1', false);
  client.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  client.send('id=1&tempo=' + tempoAberto);
}, true);

Example with sendBeacon:

var aberturaPagina;

window.addEventListener('load', function () {
  aberturaPagina = new Date().getTime();
});

window.addEventListener('unload', function () {
  var fechoPagina = new Date().getTime();
  var tempoAberto = (fechoPagina - aberturaPagina) / 1000;
  navigator.sendBeacon('http://requestb.in/1a4i8zc1', 'id=1&tempo=' + tempoAberto);
}, true);

Reference

link

    
19.02.2016 / 00:51