Capture Script Opening Time

Asked

Viewed 51 times

1

Hello, everybody.

I am trying to create a project, whose function is to identify the time the page is open (eg if it was 1 or 2 minutes open). When closed, save time information in the database.

However, I am a negation with javascript, jquery and the like. Follow the example code:

<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
  var aberturaPagina;
  $(window).ready(function () {
    aberturaPagina = new Date().getTime();
  });
  $(window).on('beforeunload', function () {
    var fechoPagina = new Date().getTime();
    var tempoAberto = (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 built this Frankenstein with codes from some forums, someone can help me fix?

1 answer

3


Browsers ignore asynchronous requests initiated in the Unload event. There are at least two ways around this: making a synchronous request or use the API Navigator.sendBacon. The latter is not supported in IE 11 but has the advantage of being asynchronous and therefore not blocking 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

https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon

  • Perfect! Thank you very much. Worked with synchronous request

Browser other questions tagged

You are not signed in. Login or sign up in order to post.