Search code examples
ajaxjqueryonbeforeunload

How to prevent page navigation until ajax call is complete


So I have an ajax call to bring down several dozen chunks of data all several megabytes in size, afterward storing the data locally via the html5 filesystem api.

I wanted to prevent the user from navigating away from the page before the ajax calls were done. I decided to explore the onbeforeunload event, to have it notify that the user should stay on the page until the ajax calls are complete. I set the following before the AJAX call and at the end/success of the AJAX call I reset the window.onbeforeunload.

window.onbeforeunload = function(){
    return "Information is still downloading, navigating away from or closing "+ 
        "this page will stop the download of data";
}

When I attempted to close the page or navigate away from the page, the pop-up message comes up as expected informing the user to stay. However, once I confirm that I want to stay on the page, the ajax calls do not resume where they left off. Is there a way to prevent the ajax calls from pausing/stopping or to continue on/restart with their executions?

I'm open to any ideas to implement desired functionality described in the title of this post.


Solution

  • Pretty sure you can create a global in the .js file like...

    var request;

    Then assign your ajax call to this variable.

    request = $.ajax{
     //Ajax
     //Stuff
     //Goes
     //Here
    }
    

    Now inside your window.unbeforeunload function, add this conditional statement.

    window.onbeforeunload = function(){
      if(!request){
        return "Request not initiated";
      }else{
        //Request is in progress...
        //You can use request.abort() if you need
      }
    }
    

    EDIT: To elaborate on on some of the methods you can use on the request object, check out this page. (for example, .done or .always may suit your circumstances)