0

I've used cordova to build a mobile app that sits entirely on the server side. This results in bad experience when the user is offline and interacts with the app. I'd like to detect when the app is about to call the server and alert the user that they are offline.

I have cordova-plugin-network-information so I know when a client is offline. I plan to handle the offline case when I know the app is going to be calling the server. The challenge is to do so in an elegant and clean way.

My app has both synchronous page loads as well as ajax calls. The brute force way would be to find all such calls and handle them with offline alerting.

Is there a way to detect a call to server (either via page load or ajas call) in Javascript so I can centralize offline handling in one place?

1 Answers1

0

Try this.

_send = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function() {

    /* Wrap onreadystaechange callback */
    var callback = this.onreadystatechange;
    this.onreadystatechange = function() {             
         if (this.readyState == 4) {

             /* We are in response; do something, like logging or anything you want */

         }

         callback.apply(this, arguments);
    }

    _send.apply(this, arguments);
}

source: JavaScript: Detect AJAX requests also check this How can I detect 'any' ajax request being completed using jQuery?

Community
  • 1
  • 1