2

I have the following code in my service worker index.js to show all the event request urls:

self.addEventListener('fetch', functin(event) {
  console.log(event.request.url);
});

With this all the request url are listed in the console. What i need is a simple if statement to check if the request url ends with .jpg. so far i tried it with if === '.jpg' or variations or with image/jpg but it does not do the trick.

4

2 回答 2

4

您可以使用String.prototype.endsWith

if (event.request.url.endsWith('.jpg')) {
    console.log(event.request.url);
}

如果这段代码要在浏览器中运行,请注意 Internet Explorer 尚不支持此功能,因此您可能需要使用polyfill

于 2017-11-07T16:24:01.010 回答
0

例如

if (event.request.url.endsWith('.jpg')) {
    console.log(event.request.url);
    //handling response you may replace it with somthing
     event.respondWith(fetch('/imgs/avatar.jpg'));
}
于 2018-01-14T14:22:50.190 回答