【问题标题】:How do I display a message in a PWA when I'm offline?离线时如何在 PWA 中显示消息?
【发布时间】:2021-07-04 02:58:54
【问题描述】:

如何在 PWA 中显示“离线”消息?

我在我的 HTML 代码中使用 Bootstrap 5 主题创建了 1 个帖子。

https://getbootstrap.com/docs/5.0/components/toasts/

我想要什么:

  • 当用户没有互联网连接时出现“您离线”消息?

如何做到这一点?这是我的代码。

index.html

<!doctype html>
<html lang="fr" class="h-100">

  <head>
    <link rel="manifest" href="/manifest.json">
    <link rel="canonical" href="https://www.mathieulebert.fr/">
    <link href="bootstrap.min.css" rel="stylesheet">
    <link href="style.css" rel="stylesheet">
  </head>

  <body class="position-relative d-flex flex-column bg-dark text-white text-center" data-bs-spy="scroll" data-target="#navbar" data-bs-offset="85" tabindex="0">

      <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="toast-header">
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-wifi-off text-danger" viewBox="0 0 16 16">
            <path d="M10.706 3.294A12.545 12.545 0 0 0 8 3C5.259 3 2.723 3.882.663 5.379a.485.485 0 0 0-.048.736.518.518 0 0 0 .668.05A11.448 11.448 0 0 1 8 4c.63 0 1.249.05 1.852.148l.854-.854zM8 6c-1.905 0-3.68.56-5.166 1.526a.48.48 0 0 0-.063.745.525.525 0 0 0 .652.065 8.448 8.448 0 0 1 3.51-1.27L8 6zm2.596 1.404.785-.785c.63.24 1.227.545 1.785.907a.482.482 0 0 1 .063.745.525.525 0 0 1-.652.065 8.462 8.462 0 0 0-1.98-.932zM8 10l.933-.933a6.455 6.455 0 0 1 2.013.637c.285.145.326.524.1.75l-.015.015a.532.532 0 0 1-.611.09A5.478 5.478 0 0 0 8 10zm4.905-4.905.747-.747c.59.3 1.153.645 1.685 1.03a.485.485 0 0 1 .047.737.518.518 0 0 1-.668.05 11.493 11.493 0 0 0-1.811-1.07zM9.02 11.78c.238.14.236.464.04.66l-.707.706a.5.5 0 0 1-.707 0l-.707-.707c-.195-.195-.197-.518.04-.66A1.99 1.99 0 0 1 8 11.5c.374 0 .723.102 1.021.28zm4.355-9.905a.53.53 0 0 1 .75.75l-10.75 10.75a.53.53 0 0 1-.75-.75l10.75-10.75z"/>
          </svg>
          <strong class="me-auto">Vous êtes hors-ligne</strong>
          <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
        <div class="toast-body text-start text-dark">
          Les informations de cette page peuvent être obsolètes.
        </div>
      </div>
    </div>

    <script src="bootstrap.bundle.min.js"></script>
    <script src="popover.js"></script>
    <script src="clipboard.min.js"></script>
    <script src="btn-clipboard.js"></script>
    <script src="pwa.js"></script>
    <script src="feed.js"></script>

  </body>

</html>

pwa.js:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('sw.js')
      .then(reg => {
        console.log('Service worker registered! ????', reg);
      })
      .catch(err => {
        console.log('???? Service worker registration failed: ', err);
      });
  });
}

sw.js:

const staticCacheName = 'v13';
const filesToCache = [
  '/',
  '/index.html',
  '/style.css',
  '/bootstrap.min.css',
  '/bootstrap.bundle.min.js',
  '/popover.js',
  '/clipboard.min.js',
  '/btn-clipboard.js',
  '/pwa.js',
  '/feed.js',
  '/icon-32.png',
  '/icon-144.png',
  '/icon-192.png',
  '/icon-512.png',
  '/iphone5_splash.png',
  '/iphone6_splash.png',
  '/iphoneplus_splash.png',
  '/iphonex_splash.png',
  '/iphonexr_splash.png',
  '/iphonexsmax_splash.png',
  '/ipad_splash.png',
  '/ipadpro1_splash.png',
  '/ipadpro3_splash.png',
  '/ipadpro2_splash.png'
];

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(staticCacheName).then(cache => {
      return cache.addAll(filesToCache);
    })
  );
});

self.addEventListener('activate', event => {
  event.waitUntil(caches.keys().then(function(cacheNames) {
    return Promise.all(
      cacheNames.filter(function(staticCacheName) {
      }).map(function(staticCacheName) {
        return caches.delete(staticCacheName);
      })
    );
  }));
});

self.addEventListener('fetch', event => {
  event.respondWith(caches.match(event.request).then(cachedResponse => {
    if (cachedResponse) {
      return cachedResponse;
    }
    return fetch(event.request);
  }));
});

self.addEventListener('message', event => {
  if (event.data.action === 'skipWaiting') {
    self.skipWaiting();
  }
});

这里有一些例子:

【问题讨论】:

    标签: javascript html progressive-web-apps service-worker offline


    【解决方案1】:

    这里有两个不同的问题——一个基于您编写的问题,一个基于您的屏幕截图。

    (尽力而为)关于缺乏连接的通知

    您可以使用offline and online events 作为触发器来显示(或隐藏)离线指标。当您只想知道当前状态时,可以检查navigator.onLine 属性,而无需等待事件。

    代码如下:

    window.addEventListener('offline', () => {
      // Show a "You're offline." toast.
    });
    
    window.addEventListener('online', () => {
      // Clear the "You're offline" toast, if it's open.
    });
    

    注意 1: 这些事件和 navigator.onLine 属性很容易出现误报,它们报告用户在线,即使他们实际上有非常不稳定的连接,或者在 wifi 网络上在一个俘虏门户后面。当您检测到用户离线时,它们可以很好地显示 UI 提示,但它们不应该用于从根本上改变您的网络应用程序的行为。

    注意 2: 这些事件和属性应该在您的 Web 应用程序的上下文中使用(即window 上下文)而不是在服务工作者中。在 service worker 的 fetch 处理程序中,您不应该编写像 if (navigator.onLine) { ... } 这样的逻辑。只需尝试调用fetch() 并相应地处理故障。

    “准备离线工作”通知

    如果您的 Service Worker 预先缓存了您的 Web 应用程序需要离线工作的所有内容,那么当 Service Worker takes control 第一次时,它应该已经准备好离线工作了——假设您的 call clients.claim() 在您的 @987654340 中@处理程序。第一次检查这种情况的最简单方法是使用如下逻辑:

    // If there isn't already a SW in control....
    if (navigator.serviceWorker && !navigator.serviceWorker.controller) {
      // As soon as a SW does take control, show the toast.
      navigator.serviceWorker.addEventListener('controllerchange', () => {
        // Show "Ready to work offline!" toast.
      });
    }
    

    稍有不同的模式是显示“新内容可用;请刷新”toast,在重新部署您的网站后,在初始 SW 获得控制权之后显示。其逻辑涉及更多,并在其他地方进行了介绍,例如在Workbox documentation

    实际显示通知

    既然你说你正在使用 Bootstrap,these examples 应该会有所帮助。

    【讨论】:

    • 我做了第一个解决方案,它有效。这是我的 HTML 文件 pastebin.com/jKYy9PLg 和这是我的 JS 文件 pastebin.com/LBypszjB 但我不熟悉 PWA。目前,即使未安装 PWA,也会出现 Toast。我希望 Toast 仅出现在实时 PWA 中。所有文件都被缓存,'这是一个 6MB 的小网站)。
    • 我在这里问了一个关于同一主题的补充问题stackoverflow.com/questions/67036429/…
    猜你喜欢
    • 2022-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 2019-04-18
    • 1970-01-01
    相关资源
    最近更新 更多