Prevent closing modal window

2

I wonder if it is possible to prevent closing the modal window of Bootstrap when refreshing the page. Because we deal with different types of users, I need this to happen so I can change the status of banco de dados . With the code below, I was able to prevent users from closing the window by clicking outside it:

data-backdrop="static"

However, I also need to prevent the window from closing when I press the F5 key.

Thank you all!

    
asked by anonymous 22.04.2015 / 02:23

1 answer

1

There is no way to close the browser or refresh 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, so you can check if the bootstrap window is visible before launching the confirmation:

In 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 usage:

<!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><scripttype="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.min.js"></script><scripttype="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">&times;</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>
    
22.04.2015 / 05:00