Function Onunload Javascript

Asked

Viewed 1,696 times

2

I’m using the function OnUnload javascript, but I can’t find an error. O 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?

2 answers

2

The onunload is not well to shoot alert(); is to trigger events like clear cookies or things like that, what you want is the 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 and yes a confirmation window, ie it is the user who decides

  • This event does not serve to detect window closing, the only way to do this is to combine the beforeunload with window.onpopstate

  • It is not possible to customize this window, see the reasons here:

  • Run script js when trying to close the window

An extra tip:

  • The tag </input> "there is no "actually elements like <br>, <hr>, <img> and <input> no closing tags, if you use HTML just 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()" />
    

0

If you want to display alert before the 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>

Browser other questions tagged

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