Ask if the user really wants to leave the page?

Asked

Viewed 9,315 times

4

I have a page where any task occurs, only it is necessary to finish it, or all process will be lost. I would like to show an Alert, as Facebook and other sites show, asking the user if they really want to leave this page or stay on it.

  • 1

    Facebook, as an example, only sends the alert when the user writes something in the comments or status and did not post. This is to avoid closing the window by accident and losing what you wrote. It is under this context that you want or is something general, regardless of the situation?

  • Exactly, in that context.

  • It is possible to do this pro F5?

3 answers

5

Use the 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

  • +1, but with this code it gives the Alert even when it is clicked on the button to send the form... I think the ap will have the same problem... have to put this exception?

  • 1

    You just need to adapt your logic within the function, this is just an example, I will edit and add an example.

  • 1

    is such a logic that it lacks... what you posted is like an incomplete answer. It is not wrong, but it is incomplete because there is a specific context.

  • 1

    I made the edit, just put the field changing the ID

  • Thanks friend!

  • You are welcome, if the answer has helped your problem, select it as an appropriate response so that others can find it if you have the same problem

Show 1 more comment

2

Under the context that the alert should be displayed if the user has a field filled, below follows a functional example with Jquery:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="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 not using libraries, so I used Jquery.

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>

Browser other questions tagged

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