How to alert the user when there's no internet connection

前端 未结 5 1061
深忆病人
深忆病人 2020-12-30 14:46

I need to alert the user with the following conditions;

  1. Request timed out
  2. No internet connection
  3. Unable to reach the server

He

相关标签:
5条回答
  • 2020-12-30 15:07

    Exactly as Simon said, you can use

    document.addEventListener("offline", youCallbackFn, false);
    

    or you can interrogate the boolean property

    navigator.onLine
    

    (Should return true or false)

    However, this technique will tell you whether device is connected. The caveat is such that device can be connected to WiFi, but the router might be offline. In that case, use a polling mechanism, like timely Ext.Ajax.request with lower timeouts. Timeout expired = offline.

    0 讨论(0)
  • 2020-12-30 15:17

    You can add 'Ext.device.Connection' in app.js of your application. And check your device is online or offline using code:

    if (Ext.device.Connection.isOnline()) {
             alert('Connected to internet');
          }
          else{
             alert('You are not connected to internet');
          }
    
    0 讨论(0)
  • 2020-12-30 15:18

    Just Embed this in your tag

    <body onoffline="alert('PLEASE CHECK YOUR INTERNET SETTING');">
    
    0 讨论(0)
  • 2020-12-30 15:19

    The best thing to do is to listen to the "offline" event. When you get the offline event you can warn your user and take whatever steps necessary to save data, etc.

    For instance, your "deviceready" callback:

    document.addEventListener("offline", function() {
        alert("No internet connection");
    }, false);
    

    This code should work for most all versions of PhoneGap. It's been in since at least the 1.0 release.

    0 讨论(0)
  • 2020-12-30 15:22

    You can use PhoneGap's NETWORK API

    The network object gives access to the device's cellular and wifi connection information.

    You can test it in the following way,

     function onDeviceReady() {
            navigator.network.isReachable("phonegap.com", reachableCallback, {});
        }
    
     // Check network status
     //
     function reachableCallback(reachability) {
         // There is no consistency on the format of reachability
         var networkState = reachability.code || reachability;
         var states = {};
         states[NetworkStatus.NOT_REACHABLE]  = 'No network connection';
         states[NetworkStatus.REACHABLE_VIA_CARRIER_DATA_NETWORK] = 'Carrier data connection';
         states[NetworkStatus.REACHABLE_VIA_WIFI_NETWORK] = 'WiFi connection';
    
         alert('Connection type: ' + states[networkState]);
      }
    
    0 讨论(0)
提交回复
热议问题