Doubts Javascript Alert

2

I was looking for a function to display an alert message to the user when he left the page and located this one in the forum:

<script>
   // Script de Alerta ao fechar a pagina... 
   window.onbeforeunload = fecharJanela 

   function fecharJanela(){  
      return "Você realmente deseja sair? os dados não salvos serão perdidos..."; 
   } 
</script>

How can I prevent this alert from being executed when I submit a submit?

The problem is happening because the system I am developing is performing a refresh on page ai by clicking the button that sends the data the browser is displaying the message

Complementing the Post .... Look at the image, the alert message is displayed when I click on "change" I wanted it not to be displayed when I clicked this button

    
asked by anonymous 18.08.2017 / 15:02

3 answers

2

This happens because your button should have some hyperlink or submit to exit the current page which makes sense.

To resolve this problem, simply cancel the onbeforeunload function in the onclick button:

document.getElementById('alterar').onclick = function () {
    window.onbeforeunload = null;
};

Or you can even associate in HTML, example:

<button type="submit" id="alterar" onclick="window.onbeforeunload = null;">Alterar</button>
    
18.08.2017 / 15:21
1

If there is a button then set the window.onbeforeunload to null when it is clicked, so the alert will not be displayed.

It does not make sense to want to do this as isset($_POST[])) , this is PHP, while the alert is already in the client, in Javascript.

This will work:

SeuElemento.addEventListener("click", function(){
    window.onbeforeunload = null;

    //... Resto do código do botão
});

Try it here. ( code)

    
18.08.2017 / 15:20
1

window.onbeforeunload = function () {
  return 'Blá Blá Blá';
}

function enviar()
{
   window.onbeforeunload = null;
   return true;
}
<form>
    <input type="text" name="name">
    <input type="submit" name="submit" onclick="enviar()">
</form>

You can add a condition in your function or clear the window.onbeforeunload event.

Example of removing event:

window.onbeforeunload = null;

Condition example:

<script>
   // Script de Alerta ao fechar a pagina... 
   window.onbeforeunload = function(){  

     if(isFormSubmit)
        return;

     return "Você realmente deseja sair? os dados não salvos serão perdidos..."; 
   } 
</script>
    
18.08.2017 / 15:27