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.
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.
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
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.
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>