如果没有网络连接,Service Worker (sw.js) 应该总是返回 offline.html 文档

如何解决如果没有网络连接,Service Worker (sw.js) 应该总是返回 offline.html 文档

我遇到了部分工作的 Service Worker 的问题。清单为将网站添加到主屏幕的用户正确定义了 start_url (https://example.com/start.html),并且 start.html 和 offline.html 也被正确缓存,并且在浏览器时都可用没有互联网连接。

如果用户离线(没有网络连接),Service Worker 会成功地为 https://example.com/start.htmlhttps://example.com/offline.html 提供服务——但是如果用户尝试打开其他任何内容(例如 https://example.com/something.html),浏览器会抛出“无法访问站点”错误消息。

我真正需要的是,如果没有网络连接,服务工作者总是返回offline.html缓存文档,无论用户试图访问哪个网址。 >

换句话说,问题在于当没有网络连接时,Service Worker 没有正确地为用户的请求提供 offline.html 服务(无论找到什么解决方案,它还需要为清单的 start_url 缓存 start.html) .

这是我当前的代码:

ma​​nifest.json

{
    "name": "My Basic Example","short_name": "Example","icons": [
        {
            "src": "https://example.com/static/ico/manifest-192x192.png","sizes": "192x192","type": "image/png"
        },{
            "src": "https://example.com/static/ico/manifest-512x512.png","sizes": "512x512","type": "image/png","purpose": "any maskable"
        }
    ],"start_url": "https://example.com/start.html","scope": "/","display": "standalone","orientation": "portrait","background_color": "#2196f3","theme_color": "#2196f3"
}

core.js

if('serviceWorker' in navigator) {
    navigator.serviceWorker.register('sw.js',{
        scope: '/'
    }).then(function(registration) {
    }).catch(function(err) {
    });
    navigator.serviceWorker.ready.then(function(registration) {
    });
}

sw.js

const PRECACHE = 'cache-v1';
const RUNTIME = 'runtime';
const PRECACHE_URLS = [
    '/offline.html','/start.html'
];
self.addEventListener('install',event => {
    event.waitUntil(
        caches.open(PRECACHE)
        .then(cache => cache.addAll(PRECACHE_URLS))
        .then(self.skipWaiting())
    );
});
self.addEventListener('activate',event => {
    const currentCaches = [PRECACHE,RUNTIME];
    event.waitUntil(
        caches.keys().then(cacheNames => {
            return cacheNames.filter(cacheName => !currentCaches.includes(cacheName));
        })
        .then(cachesToDelete => {
            return Promise.all(cachesToDelete.map(cacheToDelete => {
                return caches.delete(cacheToDelete);
            }));
        })
        .then(() => self.clients.claim())
    );
});
self.addEventListener('fetch',event => {
    if(event.request.url.startsWith(self.location.origin)) {
        event.respondWith(
            caches.match(event.request).then(cachedResponse => {
                if(cachedResponse) {
                    return cachedResponse;
                }
                return caches.open(RUNTIME).then(cache => {
                    return fetch(event.request).then(response => {
                        return cache.put(event.request,response.clone()).then(() => {
                            return response;
                        });
                    });
                });
            })
        );
    }
});

有什么想法吗?谢谢!

解决方法

您的大部分代码都按预期工作,但您需要检查一下用户是否正在请求 start.html。我从 Create an offline fallback page 获取代码并对其进行了修改以满足您的要求。

// Incrementing OFFLINE_VERSION will kick off the install event and force
// previously cached resources to be updated from the network.
const OFFLINE_VERSION = 1;
const CACHE_NAME = "offline";
// Customize this with a different URL if needed.
const START_URL = "start.html";
const OFFLINE_URL = "offline.html";

self.addEventListener("install",(event) => {
  event.waitUntil(
    (async () => {
      const cache = await caches.open(CACHE_NAME);
      // Setting {cache: 'reload'} in the new request will ensure that the
      // response isn't fulfilled from the HTTP cache; i.e.,it will be from
      // the network.
      await Promise.all([
        cache.add(new Request(OFFLINE_URL,{ cache: "reload" })),cache.add(new Request(START_URL,]);
    })()
  );
  // Force the waiting service worker to become the active service worker.
  self.skipWaiting();
});

self.addEventListener("activate",(event) => {
  event.waitUntil(
    (async () => {
      // Enable navigation preload if it's supported.
      // See https://developers.google.com/web/updates/2017/02/navigation-preload
      if ("navigationPreload" in self.registration) {
        await self.registration.navigationPreload.enable();
      }
    })()
  );

  // Tell the active service worker to take control of the page immediately.
  self.clients.claim();
});

self.addEventListener("fetch",(event) => {
  // We only want to call event.respondWith() if this is a navigation request
  // for an HTML page.
  if (event.request.mode === "navigate") {
    event.respondWith(
      (async () => {
        try {
                  
          // First,try to use the navigation preload response if it's supported.
          const preloadResponse = await event.preloadResponse;
          if (preloadResponse) {
            return preloadResponse;
          }

          // Always try the network first.
          const networkResponse = await fetch(event.request);
          return networkResponse;
        } catch (error) {
          // catch is only triggered if an exception is thrown,which is likely
          // due to a network error.
          // If fetch() returns a valid HTTP response with a response code in
          // the 4xx or 5xx range,the catch() will NOT be called.
          console.log("Fetch failed; returning cached page instead.",error);

          const cache = await caches.open(CACHE_NAME);
          if (event.request.url.includes(START_URL)) {
            return await cache.match(START_URL);
          }
          return await cache.match(OFFLINE_URL);
        }
      })()
    );
  }

  // If our if() condition is false,then this fetch handler won't intercept the
  // request. If there are any other fetch handlers registered,they will get a
  // chance to call event.respondWith(). If no fetch handlers call
  // event.respondWith(),the request will be handled by the browser as if there
  // were no service worker involvement.
});

有一点需要注意,一旦 start.html 在首次安装 Service Worker 时被缓存,它将不会再次更新,直到 Service Worker 更新。这意味着您的用户在离线并加载您的应用程序时可能会看到旧的/过时的 start.html。您可能想对 start.html 使用 network first strategy

你可以试试working demosource

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res