There is no way to prevent you from closing the browser or updating the page, but you can send the user a confirmation window, for example:
window.onbeforeunload = function() {
return "Você não salvou a sua tarefa, gostaria mesmo de sair?";
};
The problem is that so the question will run in any situation then you can check if the bootstrap window is visible before launching the confirmation:
This way the confirmation only appears if the modal window is open:
$(window).bind("beforeunload", function() {
if ($("#myModal").is(":visible")) {
return "Você não salvou a sua tarefa, gostaria mesmo de sair?";
}
});
Example of use:
<!DOCTYPE html>
<html>
<head>
<title>Exemplo simples</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(window).bind("beforeunload", function() {
if ($("#myModal").is(":visible")) {
return "Você não salvou a sua tarefa, gostaria mesmo de sair?";
}
});
</script>
</head>
<body>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Ver janela
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</body>
</html>
It is not possible to "keep" it open because by pressing F5 a new page is "generated". What you can try to do is save the information that the modal is open to when the page loads once again, automatically display it.
– Rafael Almeida