已安装的 PWA 无法离线启动

4
我用 webpack 离线插件制作了一个 PWA,并进行了如下配置:
// Put it in the end to capture all the HtmlWebpackPlugin's
// assets manipulations and do leak its manipulations to HtmlWebpackPlugin
new OfflinePlugin({
  ServiceWorker: {
    events: true,
  },
  relativePaths: false,
  publicPath: '/',
  appShell: '/',

  // No need to cache .htaccess. See http://mxs.is/googmp,
  // this is applied before any match in `caches` section
  excludes: ['.htaccess'], // index.html

  caches: {
    main: [':rest:'],

    // All chunks marked as `additional`, loaded after main section
    // and do not prevent SW to install. Change to `optional` if
    // do not want them to be preloaded at all (cached only when first loaded)
    additional: ['*.chunk.js'],
  },

  // Removes warning for about `additional` section usage
  safeToUseOptionalCaches: true,
  autoUpdate: true,
}),

new WebpackPwaManifest({
  name: 'my_app_name',
  short_name: 'my_app_short_name',
  description: 'my_app_description',
  background_color: '#364150',
  theme_color: '#b1624d',
  icons: [
    {
      src: path.resolve('app/images/icon-512x512.png'),
      sizes: [72, 96, 120, 128, 144, 152, 167, 180, 192, 384, 512],
    },
  ],
}),

所以服务工作者正在工作,我可以在Chrome开发工具中看到它。 Chrome识别了PWA,并且当我导航到我的URL(由Heroku托管在https中)时,Chrome会在移动设备上提示安装建议。 然后我将应用程序安装到我的Android手机上,登录并像往常一样使用它。当我离线时,一切仍然正常运行,我可以在整个应用程序中导航,我可以将其最小化并重新打开,到目前为止一切都很好。 当我关闭我的应用程序(使用任务管理器)时,我处于离线状态,然后打开它,它会提示白色页面或无连接提示。 有什么提示吗? 此外,它是如何工作的?每次我单击已安装的PWA时,它都会检查我是否连接并下载(如果存在)应用程序的更新版本?
1个回答

1
根据此链接,在处理获取事件时,需要为根请求添加一个额外条件。
self.addEventListener('fetch', function(event) {
    // … either respond with the cached object or go ahead and fetch the actual URL
    event.respondWith(
        caches.match(event.request).then(function(response) {
            if (response) {
                // retrieve from cache
                return response;
            }

            // if not found in cache, return default offline content (only if this is a navigation request)
            if (event.request.mode === 'navigate') {
                return caches.match('./index.html');
            }

            // fetch as normal
            return fetch(event.request);
        })
    );
});

此外,从这个线程中,如果服务工作者未在根路径(/)上运行,您需要在客户端JavaScript中指定所需的scope参数,以便连接到服务工作者。


在导航请求模式下,即使用户连接到互联网,此模式也将始终尝试返回index.html而不进行缓存。正确的方法是无条件地尝试获取,如果失败,则返回离线内容。请参考此答案:https://dev59.com/jlYO5IYBdhLWcg3wTfxv#46098981 - 95faf8e76605e973

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接