C# MVC Run Function (Logout) When Closing Browser

Asked

Viewed 1,861 times

5

I am in a service system and need a help to understand how I can call some event (Javascript / jQuery / Or not) at the time a user closes the browser without logging "correct" by the system...

Att.

3 answers

4

You can use the function Unload() of jQuery to capture the moment browser is closed, and from this moment, you make a call via ajax to the Action desired. Before, you check whether the browser has been updated or closed at once.

Would that be the code:

<script>
            (function ($) {
        var refreshKeyPressed = false;
        var modifierPressed = false;

        var f5key = 116;
        var rkey = 82;
        var modkey = [17, 224, 91, 93];

        //Verifica se submit
        var submitting = false;
        $('form').submit(function (e) {
            submitting = true;
        });

        // verifica as chaves de atualização
        $(document).bind(
            'keydown',
            function (evt) {
                // busca por atualização
                if (evt.which == f5key || window.modifierPressed && evt.which == rkey) {
                    refreshKeyPressed = true;
                }

                // checa se há modificação
                if (modkey.indexOf(evt.which) >= 0) {
                    modifierPressed = true;
                }
            }
        );

        // verifica as chaves de atualização
        $(document).bind(
            'keyup',
            function (evt) {
                // verifica a chave
                if (evt.which == f5key || evt.which == rkey) {
                    refreshKeyPressed = false;
                }

                // checa se há modificação
                if (modkey.indexOf(evt.which) >= 0) {
                    modifierPressed = false;
                }
            }
        );
        $(window).bind('beforeunload', function (event) {
            var message = "not refreshed";

            //submit é falso, realiza ação
            if (!submitting) {
                //Se atualizou entra aqui
                if (refreshKeyPressed) {
                    message = "refreshed";

                    //retorna a mensagem apenas para testes
                    event.returnValue = message;
                    return message;
                }

                //Senão, chama a action
                //$.ajax({
                //    url: BASE_URL + 'Testes/Aqui',
                //    type: 'POST'
                //});

                event.returnValue = message;
                return message;
            }

        });
    }(jQuery));
</script>

The script is self-explanatory, but a brief explanation: First it filters possible update events such as F5, etc. After that, it checks whether the Submit of his view. If he finds himself in any such clauses, he calls his action via ajax .

Example in Jsfiddle.

References:

Soen,
Soen²

  • Randrade, I tried that. But the Unload is also called at the time of a refresh, then becomes half "invalid" the action...

3

Add to your script:

   window.onbeforeunload = function () {
        return "Você realmente deseja fechar?";
    };
  • Maybe I didn’t make myself clear, but in reality I would like to call an MVC Action to log the user’s logout, even to be able to register in the database this "exit" time of the user, you understand...

  • I get it, I’m going to do a little research, because I may have to use setTimeOut, I’ll see, a moment

  • Okay. In the company where I work there is a system that when closing the browser, a new window is opened and the session cleaning takes place and is closed soon after, all automatically! : The

  • and you cannot manipulate the cleaning of that session, enjoy the session and log out the user ?

  • Thiago, you refer to Session_end of Global.asax?

  • @Antôniofilho exactly.

  • So, I even tried, but the problem is that I have to recover the user id logged in to the cookie (Authenticationforms) and then record it in the database... And as far as I know, Session_end is not sure of its execution... Note: I don’t know if it’s a good practice to have bank connection properties in my Global.asax.

Show 3 more comments

1

There is no 100% reliable way to do this as on a desktop system, an alternative in the web environment is to use the event unload() that desexib the page, with some filters is close to the desired.

I had this problem last week I found this code.

Basically what it does is check if the mouse pointer is outside the page area and filter some keys not to perform the action.

$(window).on('mouseover', (function () {
    window.onbeforeunload = null;
}));
$(window).on('mouseout', (function () {
    window.onbeforeunload = ConfirmLeave;
}));
function ConfirmLeave() {
    return "";
}
var prevKey="";
$(document).keydown(function (e) {            
    if (e.key=="F5") {
        window.onbeforeunload = ConfirmLeave;
    }
    else if (e.key.toUpperCase() == "W" && prevKey == "CONTROL") {                
        window.onbeforeunload = ConfirmLeave;   
    }
    else if (e.key.toUpperCase() == "R" && prevKey == "CONTROL") {
        window.onbeforeunload = ConfirmLeave;
    }
    else if (e.key.toUpperCase() == "F4" && (prevKey == "ALT" || prevKey == "CONTROL")) {
        window.onbeforeunload = ConfirmLeave;
    }
    prevKey = e.key.toUpperCase();
});

The code was taken from: Soen - Trying to Detect browser close Event

  • rray, I tested this code snippet in Chrome, and it was identical to a normal onbeforeunload... : S

  • @Antôniofilho in firefox tbm?

  • I’m sorry for forever answering. But I made some changes to this method and tals, but it is not yet possible to capture Ctrl+W, Alt+F4 or commands to exit the browser window. My intention is not to question the user when closing the browser, but to "run a simple Alert', that is, detect the moment when the Ctrl+W keys are triggered, even if it displays Alert and then close the browser.

Browser other questions tagged

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