【问题标题】:Installed pwa won't launch offline安装的 pwa 不会离线启动
【发布时间】:2019-06-19 01:30:18
【问题描述】:

我使用 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 devtools 上看到它。 pwa 被 chrome 识别,当我导航到我的 url(由 https 中的 heroku 托管)时,chrome 会提示在移动设备上提供安装建议。 然后我将应用程序安装到我的安卓手机上,登录并像往常一样使用它。当我离线时一切仍然有效,我可以浏览我的应用程序,我可以最小化它并重新打开,到目前为止一切都很好。 当我关闭我的应用程序(使用任务管理器)时,我会离线,然后打开它会提示白页或无连接提示。 有小费吗? 在成瘾中,它实际上是如何工作的?每次我单击已安装的 pwa 时,它都会检查我是否有连接并下载(如果存在)较新版本的应用程序?

【问题讨论】:

    标签: android webpack service service-worker progressive-web-apps


    【解决方案1】:

    基于此link,在处理 fetch 事件时,您需要根请求的额外条件。

    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);
            })
        );
    });
    

    同样来自这个thread,如果它不在根 (/) 路径上运行,则在连接到 serviceworker 时,您需要在客户端 JavaScript 中指定一个必需的 scope 参数。

    【讨论】:

    • 在未缓存响应的导航请求模式下,即使用户连接到互联网,它也将始终尝试返回 index.html。正确的方法是无条件地尝试获取,然后如果失败,即当您返回离线内容时。看到这个答案:stackoverflow.com/a/46098981/8680805
    猜你喜欢
    • 2022-06-13
    • 2023-02-26
    • 1970-01-01
    • 2015-12-20
    • 2023-03-05
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多