Service Worker 图像状态码

Service worker image status code

我尝试用服务人员检测图像的错误 404。 有没有办法获取图像提取的状态代码?

self.addEventListener('fetch', function(event) {

    console.log('Handling fetch event for %s', event.request.url);

    event.respondWith(
        fetch(event.request).then(function(response) {

            if (response.status == 200) {
                return response;                    
            }
            else {
                /* return some default image */
            }

        })        
    );

});

此代码适用于 html 个文件,但是当它获取图像时,状态代码始终为 0。有没有办法获取图像的状态代码?为了简化示例,我删除了缓存和其他所有内容。

这是我尝试加载的示例页面:

<body>
    <!-- This image is working -->
    <img src="http://www.google.ca/images/srpr/logo11w.png">
    <!-- This image returns 404 -->
    <img src="http://www.google.ca/images/srpr/00000.png">
</body>

所以 html 页面本身的状态是 200 但两个图像 return 状态都是 0.

根据the fetch spec, a status of 0 represents an error. You may want to check the status message. My guess is that this is a CORS-related error, since you're fetching from a third-party site. From Matt Gaunt's Introduction to Service Worker

By default, fetching a resource from a third party URL will fail if it doesn't support CORS. You can add a non-CORS option to the Request to overcome this, although this will cause an 'opaque' response, which means you won't be able to tell if the response was successful or not.

按照他的建议尝试设置 mode: 'no-cors'

您将返回一个 opaque filtered response,这在您的请求不使用 CORS 时是预期的。在这种情况下,0status 是有意含糊的——如果使用了真实的状态代码,那么在没有 CORS 的情况下无法获得的信息将会泄露。

fetch 规范 issue 中有一些背景知识。