How to prevent the user from closing a page without sending the form, but without using a dialog?

1

I have an HTML page that has a form. I need to prevent that after the user completes this form, it click on another button of the page that is not the "Save".

I found a script that solved this, but it can easily be circumvented. In this script, a default browser dialog appears, and in this dialog has a checkbox where the user can mark so that the page does not create new dialogs. After testing, I saw that when this checkbox is marked, the script no longer works and the user can exit the page without saving the form.

Below the script I used:

var init_form = $('#processosForm').serialize();

$(':submit').click(function() {
  window.onbeforeunload = null;
});

window.onbeforeunload = function(){
  var check_form = $('#id_form').serialize();
  if( check_form === init_form )
        return null;
  return 'Os dados alterados ainda não foram salvos, deseja permanecer nesta página?';
};

I would like to know some other way to have this same result, but without the possibility of the user cheating. The alternative may be in pure javascript ... or jquery ... I have no restrictions on that.

My idea is to create a modal (Jquery or Bootstrap) and when the user clicks any other button on the screen other than the "save", this modal would appear. The modal structure would be basically like this:

<!-- Modal -->
<div class="modal fade" id="confirmaSaida" role="dialog">
 <div class="modal-dialog">
  <!-- Modal content-->
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">&times;</button>
      <h4 class="modal-title">Tem certeza de que deseja sair dessa tela?</h4>
    </div>
    <div class="modal-body">
    Você tem dados que ainda não foram salvos. Clique em "Salvar" antes de sair dessa página.
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-danger" data-dismiss="modal">Sair sem salvar</button>
    </div>
  </div>

</div>

The problem is: how to make this modal appear when the user clicks other screen buttons?

    
asked by anonymous 06.01.2016 / 17:57

1 answer

1

You can not prevent the user from leaving your site, as this would cause the browser to stop responding. The only way to stop browser execution is with the browser's native dialog - and all newer browsers have the option to disable for security (to avoid abuses).

The action looks like this: The user requests to exit the page = > the onbeforeunload output function is triggered, the return value within that function sets the output confirmation dialog message.

What can be done is an infinite loop in the onbeforeunload function so that it does not return, but in safe browsers only the tab will be locked, and it will still be possible to forcibly close the locked tab.

    
07.01.2016 / 16:54