Execute function when closing the window

Asked

Viewed 136 times

1

I am trying to run the function below so that when the user closes the page, an alert will appear asking if you want to save before leaving, by clicking on OK, the progress of the form will be saved in the localStorage and by clicking on Cancelar, the window will be closed as the user requested, but it is not working at all, what is wrong? It is possible to do this?

Code:

<form id="msform">
<input id="um" /><br>
<input id="dois" />
</form>
window.onbeforeunload = saida;

function saida(){

   var sair = confirm("Deseja salvar antes de sair?");

   if (sair == true) {
      [].forEach.call(document.querySelector('#msform').elements, function(el) {
         localStorage.setItem(el.id, el.value);
      });
   } else {
      window.close();
   }

}
  • Read this answer I had made a while ago, will understand how the onbeforeunload works.

1 answer

0

I put some alerts in your code, see what displays in each case, basically you will debug the code.

window.onbeforeunload = saida;

function saida(){
 alert ('ok1')
   var sair = confirm("Deseja salvar antes de sair?");

   if (sair == true) {
     alert ('ok2')
[].forEach.call(document.querySelector('#msform').elements, function(el) {
         localStorage.setItem(el.id, el.value);
      });
   } else {
      alert ('ok3')
      window.close();
   }

}
  • Still not working

Browser other questions tagged

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