ibrahim
ibrahim

Reputation: 343

Cancel/remove/disable beforeunload eventlistener if AJAX response is successful

In my Android web app page, browser can warn user in case of wrongly refresh the page:

<script>
    window.onbeforeunload = function(e) {
       var dialogText = 'Dialog text here';
       e.returnValue = dialogText;
       return dialogText;
    };
</script>

It's working good. But in my AJAX call (if save process is success) I'm automatically redirecting user to home page. (user shouldn't stay in same page) My working code is:

$.ajax({
       url: '{{ url()->current() }}',
       type: 'POST',
       data: $('#mainForm').serializeArray(),
       beforeSend: function (xhr) {
              $.LoadingOverlay("show");
       },
       error: function(xhr,status,error){ 
              $.LoadingOverlay("hide");
              swal('Error','bla bla bla!', 'error');
       },
       success: function(result, status, xhr){
              if(result.hasOwnProperty('success')){ 
                   /* Here i want to disable beforeunload */
                   window.location.href = "{{ url('m') }}";
              }else if(result.hasOwnProperty('error')){
                   swal('Error',result.error, 'error');
              }else{
                   swal('Error',"bla bla bla ", 'error');
              }
       },
       complete: function(xhr){
              $.LoadingOverlay("hide");
       }
 });

In success condition, I don't want user to decide stay this page or redirect to new location. I want to automatically redirect user to new location.

I've tried this solutions:

window.onbeforeunload = function () {
  // blank function do nothing
}

OR

window.onbeforeunload = null;

OR this

function functionToRun(e){
     if(sessionStorage.token != "abide" ){
        // call api
     }
}

window.removeEventListener("beforeunload",functionToRun);

I couldn't solve my problem.

Upvotes: 0

Views: 314

Answers (1)

ltamajs
ltamajs

Reputation: 1341

removeEventListener should work, but you should name your beforeunload handler:

function onBeforeUnload(e) {
    var dialogText = 'Dialog text here';
    e.returnValue = dialogText;
    return dialogText;
};    
window.addEventListener('beforeunload', onBeforeUnload);

And in your success callback:

window.removeEventListener('beforeunload', onBeforeUnload);

Upvotes: 2

Related Questions