渐进式Web应用程序:如何检测和处理连接何时再次启动

Han*_*ung 10 javascript offlineapps progressive-web-apps

使用PWA,现在我们可以在离线模式下关闭设备连接.但问题是当用户修复他们的连接时,我们如何检测它并自动重新加载/重新激活应用程序,以便用户不必自己动手?

ton*_*y19 32

你可以监视 offlineonline事件,这是广泛的支持:

// Test this by running the code snippet below and then
// use the "Offline" checkbox in DevTools Network panel

window.addEventListener('online', handleConnection);
window.addEventListener('offline', handleConnection);

function handleConnection() {
  if (navigator.onLine) {
    isReachable(getServerUrl()).then(function(online) {
      if (online) {
        // handle online status
        console.log('online');
      } else {
        console.log('no connectivity');
      }
    });
  } else {
    // handle offline status
    console.log('offline');
  }
}

function isReachable(url) {
  /**
   * Note: fetch() still "succeeds" for 404s on subdirectories,
   * which is ok when only testing for domain reachability.
   *
   * Example:
   *   https://google.com/noexist does not throw
   *   https://noexist.com/noexist does throw
   */
  return fetch(url, { method: 'HEAD', mode: 'no-cors' })
    .then(function(resp) {
      return resp && (resp.ok || resp.type === 'opaque');
    })
    .catch(function(err) {
      console.warn('[conn test failure]:', err);
    });
}

function getServerUrl() {
  return document.getElementById('serverUrl').value || window.location.origin;
}
Run Code Online (Sandbox Code Playgroud)

处理这个的一种技术:

  • 离线活动

    • 显示离线图标/状态
    • 仅启用可脱机使用的功能(通过缓存数据)
  • 在线活动

    • 显示在线图标/状态
    • 启用所有功能


Nic*_*zey 17

小心online事件,只告诉设备是否连接.它可以连接到WiFi热点而无需实际的Internet连接(例如,因为凭据).

  • 您可以在触发在线事件时ping您的服务器,以验证您是否可以访问您的数据. (5认同)