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 this 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 have no experience with cookies, I gave a study about and I took this example code. In the code it expires the cookie in 14 days, I need the cookie to expire when the application is closed. I tried using "Onunload" in the layout body, but it does not show the selection screen when opening the application again, I do not know if it is actually deleting the cookie. Follow the code I used in onunload:
Code on the Body:
<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);
}
Some solution ?
ps: when I used Onunload I removed the Expirate from the code that generates the cookie
Got it, I managed to make that function work just by quoting the onunload, it was not recognizing the name of the cookie, ai now whenever the browser closes and opens dnv, it incializes the cookie, but really this question that you spoke should be considered
– Dan Oliveira
@Danoliveira the onunload problem is that it is also not guaranteed, even more if the user "kill" the main process, that would close everything, for example logoff, or this using on a mobile where it is usually possible to finish everything without confirmation, when you close the browser app
– Guilherme Nascimento
Got it, thanks for the help Brother! I’ll keep it even longer, more guaranteed
– Dan Oliveira