Redirect to another page

2

Colleagues.

How would I make the user to close the browser or tab, was directed to another page, but that did not work when giving the F5. I say this because I have a system that has the status online and offline and many of them are closing by the browser or tab and status is still online. The idea is when to close the browser or tab, be directed to a page where I could disconnect it from the system and close the browser.

Looking from here and there, I found this code, but it is not working, but it can be a starting point ... see:

<script>
var check;
function fechasess(url,e) {

if (url == 'f5') { //Entra quando uma tecla é apertada

if (e.keyCode == 116) { check = 1; } //Verifica se a tecla é F5 no IE, se for bloqueia o logout

if (e.which == 116) { check = 1; } //Verifica se a tecla é F5 no FF, se for bloqueia o logout

}else if (url == 'logout.php') { //Entra quando o onunload ativa

if (check != 1) { document.location=(url); } //Verifica se deve ativar o logout ou não
}else{ //Entra quando for um link
check = 1; //Bloqueia o logout 

document.location=(url); //Redireciona o link
}
}
</script>
<body onkeydown="fechasess('f5',event)" onkeypress="fechasess('f5',event)" onbeforeunload="fechasess('logout.php')" onunload="fechasess('logout.php')"> 
    
asked by anonymous 13.05.2015 / 01:24

1 answer

3

The ideal would be not to redirect them, but to make a request via ajax to this page and from there to update the status.

To intercept when the browser is closing and make an AJAX request, you can use the following code:

window.onunload = function(ev) {
  var request = new XMLHttpRequest();
  request.open('POST', '/caminho/para/update/do/status.php', true);
  request.send();
  request.onreadystatechanged = function(e) {
     if(this.status === 200 || this.statusText === 'OK') {
       // deu tudo certo
     } else {
       // muito provável que algo tenha dado errado
     }
  }
}

While not 100% required, jQuery could also be used in place of VanillaJS.

    
13.05.2015 / 21:56