将服务工作者请求中的响应修改为图像

Modifying responses in service worker requests to be an image

您好,先谢谢您了。

我的问题是关于使用 ServiceWorker 响应网络请求。如果是文本或 html,我可以处理它,但是当我尝试处理 image 时,我失败,这是我的代码:

self.addEventListener('fetch', function(event){
event.respondWith(
    fetch(event.request).then(function(response){
        if(response.status === 404){
            return new Response('The page wasn\'t found');
        }
        return response;  
     }).catch(function(){
            return new Response('The network is totally failed');
     })
    );
 });

上面的代码片段在处理文本和 html 时有效,但是当我尝试使用 image 它带来全黑的屏幕。这是我用过的,但没有用。

self.addEventListener('fetch', function(event){
event.respondWith(
    fetch(event.request).then(function(response){
        if(response.status === 404){
            return new Response('/imgs/sunset.gif', {headers:{'Content-Type':'image/gif'}});
        }
        return response;  
     }).catch(function(){
            return new Response('The network is totally failed');
     })
    );
 });

希望你能帮助我知道我错过了什么。谢谢。

您需要更换线路:

return new Response('/imgs/sunset.gif', {headers:{'Content-Type':'image/gif'}});

作者:

return new Response("<img src='/imgs/sunset.gif'/>", {headers:{'Content-Type': 'text/html'}});

您想在您的页面中显示一个 gif,因此您必须添加一个 html 内容并告知其来源 src。

或者更简单的解决方案,你只能这样写:

return fetch('/imgs/sunset.gif');

您可以使用 fetch 从如下文件中获取图像或 gif。

self.addEventListener('fetch', function(event) {
  event.respondWith(
    fetch(event.request).then(function(response) {
      if (response.status === 404) {           
        return fetch("/path/to/404error.gif");
      }
      return response;
    }).catch(function() {
      return new Response("Uh oh, that totally failed!");
    })
  );
});

我一直在寻找类似的解决方案和以下工作:

self.addEventListener('fetch', function(event) {
  event.respondWith(
    fetch(event.request).then(function(response) {
      if (response.status === 404) {
        return fetch('/imgs/sunset.gif');
      }
      return response;
    }).catch(function() {
      return new Response("Uh oh, that totally failed!");
    })
  );
});