Remove Cookie when closing browser

1

When the application starts, I need to open a modal for the user to choose an environment, so I created a cookie in JS to store if it is the first time the user opened the application, follow the code:

 window.onload = function() {

        var cookies = document.cookie;

        // Verifica se o cookie existe
        if (cookies.indexOf("usuarioVisualizouModal") == -1) {
            // Entra aqui caso o cookie não exista no  navegador do usuário

            // Crio um objeto Date do Javascript pegando a data de hoje e incrementando + 14 dias nessa data
            var diasparaexpirar = 14;
            var expiracao = new Date();
            expiracao.setTime(expiracao.getTime() + (diasparaexpirar * 24 * 60 * 60 * 1000));

            // Converte a data para string
            expiracao = expiracao.toUTCString();

            // Crio o cookie com a data de expiração
            document.cookie = 'usuarioVisualizouModal=SIM;  path=/';

            // Exibo o modal
            var url = '/Facility/ActiveFacility';
            $('#ModalBody').html('<iframe width="100%" height="100%" frameborder="0" allowtransparency="true" src="' + url + '"></iframe>');
            $("#OpenModal").modal("show");
        }
    };

I do not have experience with cookies, I studied it and got this sample code. In the code it expires the cookie in 14 days, I need the cookie to expire when the application is closed. I tried to use "Onunload" in the body of the layout, however it does not display the selection screen when opening the application again, I do not know if it is actually deleting the cookie. Here is the code I used in onunload:

No Body Code:

<body onunload="deleteCookie(usuarioVisualizouModal);">

Function:

         function deleteCookie(nome){
   var exdate = new Date();
   exdate.setTime(exdate.getTime() + (-1 * 24 * 3600
      * 1000));
   document.cookie = nome + "=" + escape("")+ ((-1
      == null) ? "" : "; expires=" + exdate);
 }

Any solution?

ps: When I used OnUnload I removed the Expirate from the code that generates the cookie

    
asked by anonymous 13.08.2018 / 15:45

1 answer

3

It is impossible to guarantee that this happens, even more if the user uses the "keep" session, when the browser reopens the tabs are restored to the last state, for example in the current browsers (08/13/2018):

Opera:

Chrome:

That is, the browser will try to keep everything at this point, as if the user had not closed, so the best way out is to work with the same time, and put a timeout to expire the cookie

    
13.08.2018 / 16:00