JavaScript OnUnload Function

2

I'm using the OnUnload function of javascript, but I can not find error. The alert should be displayed before closing the browser, window, or loading another address bar, correct?

function close(){
  alert("Não vá embora, inscreva-se...");
}

<body onunload="close()">
  <input type="button" value="Aula JS - Eventos" onclick="clique()"></input>
  <br>
  <input type="text" name="txt_aula" onfocus="entra()" onblur="sai()"></input>
</body>

Does anyone know if this function still works in javascript?

    
asked by anonymous 05.05.2016 / 18:21

2 answers

2

onunload is not good for firing alert(); is for triggering events like clearing cookies or the like, what you want is onbeforeunload , do so:

<script>
window.onbeforeunload = function () {
    return "Não vá embora, inscreva-se...";
};
</script>

<body>
<input type="button" value="Aula JS - Eventos" onclick="clique()">
<br>
<input type="text" name="txt_aula" onfocus="entra()" onblur="sai()">
  

Note that:

     
  • The beforeunload does not show a alert but a confirmation window, that is the user who decides

  •   
  • This event is not intended to detect window closure, the only way to do this is to combine beforeunload with window.onpopstate

  •   
  • Can not customize this window, see the reasons here:

  •   
  • Run js script when you try to close the window

  •   

An extra tip:

  • The tag </input> "does not exist", actually elements like <br> , <hr> , <img> and <input> does not have closing tags , if using HTML simply do so:

    <input type="button" value="Aula JS - Eventos" onclick="clique()">
    <br>
    <input type="text" name="txt_aula" onfocus="entra()" onblur="sai()">
    
  • If you use XHTML do so:

    <input type="button" value="Aula JS - Eventos" onclick="clique()" />
    <br />
    <input type="text" name="txt_aula" onfocus="entra()" onblur="sai()" />
    
05.05.2016 / 18:27
0

If you want to display alert before User leaves the page, use onbeforeunload.

window.onbeforeunload = close;

function close(){
  return "Não vá embora, inscreva-se...";
}
<body>
<input type="button" value="Aula JS - Eventos" onclick="clique()"></input>
<br>
<input type="text" name="txt_aula" onfocus="entra()" onblur="sai()"></input>
    
05.05.2016 / 18:29