Ask if the user really wants to leave the page?

4

I have a page where any task occurs, only it needs to be finalized, or every process will be lost. I would like to show an alert, like Facebook and other websites show, asking the user if they want to leave this page or stay in it.

    
asked by anonymous 16.09.2015 / 20:29

3 answers

5

Use window.onbeforeunload

Html:

<textarea id="comentario"></textarea>

<a href="">Sair da página</a>

Javascript:

window.onbeforeunload = confirmExit;
function confirmExit()
{
    if(document.getElementById("comentario").value != ""){
        return "Deseja realmente sair desta página?";
    }
}

Example link working: JsFiddle

    
16.09.2015 / 20:47
2

Under the context that the alert should be displayed if the user has a filled field, the following is a functional example with JQuery:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script><scripttype="text/javascript">

$(window).bind("beforeunload", function() { 
    console.log("length", $("#foo").val().length);
    if ($("#foo").val().length > 0)
        return "Do you really want to close?";
})
</script>
</head>
<body>

<input id="foo" type="text" value="" size="50" />

</body>
</html>

The question does not specify the non-use of libraries, so I used JQuery.

    
16.09.2015 / 22:58
0

Put this script on your page and test:

   <script language="JavaScript">
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    return "Se você fechar o navegador, seus dados serão perdidos. Desena Realmente sair?";
  }
</script>
    
16.09.2015 / 22:55