【问题标题】:Enabling service worker using workbox使用工作箱启用服务工作者
【发布时间】:2017-12-27 06:09:11
【问题描述】:

使用 webpack 作为构建系统的 react PWA。对于 Service Worker,我们使用的是 workbox 版本 2.1.2。

  • 拥有一个使用 JSON 响应的 GET api http://localhost:5000/dist/abc/123/。用

    注册了路由
    'use strict';
     importScripts('workbox-sw.prod.js');
     const workboxSW = new WorkboxSW({
        clientsClaim: true,
        skipWaiting: true
     });
     workboxSW.LOG_LEVEL = 'debug';
     workboxSW.precache([]);
     workboxSW.router.registerRoute(
              'http://localhost:5000/dist/abc/123',
               workboxSW.strategies.staleWhileRevalidate({
                     cacheName: 'apis',
                     cacheExpiration: {
                         maxEntries: 50,
                         maxAgeSeconds: 30 * 24 * 60 * 60
                     },
                     cacheableResponse: {statuses: [0, 200]}
                })
             );
    self.addEventListener('install', () => {
       self.skipWaiting();
    });
    

确保加载了新的 Service Worker。当 API 调用返回状态为 200 时,缓存存储下没有创建缓存 apis。因此它也不能离线工作,请参阅No cache "apis" 验证如下,

  • 请求更正 URL
  • 在 Service Worker 安装阶段代码流命中 registerRoute
  • 没有错误消息。调试消息也没有给出任何线索。有什么方法可以启用更多调试?
  • Service Worker 注册在合适的范围内,Debug 消息Service Worker registration successful with scope: http://localhost:8081/dist/

API:http://localhost:5000/dist/abc/123

调用的 API,http://localhost:5000/dist/abc/123/。请注意,它是跨站点调用,调用的基本页面是http://localhost:8000。如前所述,API 调用成功并返回状态为 200 的响应。

我对 serviceworker/workbox 很陌生。对此的任何指示都非常感谢。

【问题讨论】:

    标签: webpack progressive-web-apps workbox


    【解决方案1】:

    您应该尝试使用 https 运行您的应用,并在您的选项中传递 cors 参数

    如 mdn 文档https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API中所述

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-07
      • 2020-07-02
      • 2017-11-22
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      相关资源
      最近更新 更多