-1

I have a problem, I need to capture the closing of my browser with JavaScript in order to close the user's current session and thus validate that only one user session is open.

What I have tried so far is to capture the closing of the browser with onload and onbeforeunload as follows:

<body onload=sesionVerified() onbeforeunload=exitSesion() class="fixed-navbar">

And the JavaScript is as follows:

function sesionVerified() {
    console.log("sesion activa"); 
}

function exitSesion() {

    setTimeout(() => {
        var idusuario = $("#txt_idusuario_general").val(); 
    }, 100);

    $.ajax({
            url: "../controlador/usuario/controlador_cerrar_sesion.php",
            type: 'POST',
            data: {
              id: idusuario
            }
          }).done(function (resp) {
            var data = JSON.parse(resp);          
          })

}
lsanchezo
  • 1
  • 2
  • `idusuario` is defined as a local variable inside the setTimeout function, so it won't be available outside that function. In addition, it's unclear why the setTimeout is there at all, since it won't complete until the ajax call is sent (and then it's too late to include the `idusuario`) – James Apr 22 '22 at 18:33

1 Answers1

0

bind to this event and run your ajax call here

window.onbeforeunload = function (e) {
    runBeforeClose(); // Your logic goes here
};

OR

jQuery .bind() has been deprecated. Use .on() instead

    $(window).on("beforeunload", function() {
        runBeforeClose(); // Your logic goes here
    });
Dean Van Greunen
  • 2,925
  • 2
  • 13
  • 25
  • 1
    It works for me, but with restrictions. It only works in Chrome and it doesn't detect when I close the browser, only the tab. Also, I've to have other tabs open before closing the web page tab, otherwise it doesn't detect me. Is it possible that i have to use `$(document).ready(function() { })` ? I'm doing the tests – lsanchezo Apr 22 '22 at 19:10