如何防止 fetch() 忽略离线页面?

发布于 2025-01-14 03:33:44 字数 1423 浏览 4 评论 0原文

下面的 JavaScript 代码使用 Fetch API 从服务器检索一些文本。

 fetch("index.php?user_id=1234", {
        method: "GET"
    }).then(function(response) {
        return response.text();
    }).then(function(output) {
        document.getElementById("output").innerHTML = output;
    });

但在网络错误期间,由于 service-worker,它会检索离线页面(offline.html)。

"use strict";

self.addEventListener("install", function() {
    self.skipWaiting();
});

self.addEventListener("activate", function(activation) {
    activation.waitUntil(

        caches.keys().then(function(cache_names) {
            for (let cache_name of cache_names) {
                caches.delete(cache_name);
            };

                caches.open("client_cache").then(function(cache) {
                    return cache.add("offline.html");
                });
        })
    );
});

self.addEventListener("fetch", function(fetching) {
    fetching.respondWith(
        caches.match(fetching.request).then(function(cached_response) {
            return cached_response || fetch(fetching.request);
        }).catch(function() {
            return caches.match("offline.html");
        })
    );
});

我想让提取请求知道网络错误。

而且我不想使用window.navigator那么,我该怎么办做?

(我更喜欢普通的解决方案。)

The JavaScript code below retrieves some texts from server by using Fetch API.

 fetch("index.php?user_id=1234", {
        method: "GET"
    }).then(function(response) {
        return response.text();
    }).then(function(output) {
        document.getElementById("output").innerHTML = output;
    });

But during network errors, it retrieves the offline page (offline.html) due to service-worker.

"use strict";

self.addEventListener("install", function() {
    self.skipWaiting();
});

self.addEventListener("activate", function(activation) {
    activation.waitUntil(

        caches.keys().then(function(cache_names) {
            for (let cache_name of cache_names) {
                caches.delete(cache_name);
            };

                caches.open("client_cache").then(function(cache) {
                    return cache.add("offline.html");
                });
        })
    );
});

self.addEventListener("fetch", function(fetching) {
    fetching.respondWith(
        caches.match(fetching.request).then(function(cached_response) {
            return cached_response || fetch(fetching.request);
        }).catch(function() {
            return caches.match("offline.html");
        })
    );
});

I want to let the fetch request know about the network error.

And I do not want to use window.navigator. So, what can I do?

(I prefer vanilla solutions.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

今天小雨转甜 2025-01-21 03:33:44

您应该构建 Service Worker 的 fetch 事件处理程序,以便仅在出现网络错误/缓存丢失原始请求时返回 offline.html是为了导航。如果原始请求不是导航,则使用 offline.html 进行响应(如您所见)将导致每次失败时都返回 HTML。

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request).then((cachedResponse) => {
      return cachedResponse || fetch(event.request);
    }).catch((error) => {
      if (event.request.mode === 'navigate') {
        return caches.match('offline.html');
      }

      throw error;
    })
  );
});

You should structure your service worker's fetch event handler so that it only returns offline.html when there's a network error/cache miss and the original request is for a navigation. If the original request is not a navigation, then responding with offline.html is (as you've seen) going to result in getting back HTML for every failure.

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request).then((cachedResponse) => {
      return cachedResponse || fetch(event.request);
    }).catch((error) => {
      if (event.request.mode === 'navigate') {
        return caches.match('offline.html');
      }

      throw error;
    })
  );
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文