服务工作者在Chrome中收到Cachebuster错误

时间:2017-01-27 01:50:34

标签: javascript caching service-worker

不可否认,我对这些东西很青睐。我试图让服务工作者显示一个离线页面,当我使浏览器脱机时出现这个错误:

无法获取/offline.html?cachebust=1485461215845

我的代码基于这篇文章:

http://deanhume.com/home/blogpost/create-a-really--really-simple-offline-page-using-service-workers/10135

我的Index.html脚本中包含此内容:

<script type="text/javascript">
// Register the service worker
if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/sw.js').then(function(registration) {
        // Registration was successful
        console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }).catch(function(err) {
        // registration failed :(
        console.log('ServiceWorker registration failed: ', err);
    });
}
</script>

我的服务工作者代码(sw.js)中有这个:

'use strict';
var cacheVersion = 1;
var currentCache = {
    offline: 'offline-cache' + cacheVersion
};
const offlineUrl = 'offline.html';

this.addEventListener('install', event => {
    event.waitUntil(
        caches.open(currentCache.offline).then(function(cache) {
            return cache.addAll([
                offlineUrl
            ]);
        })
    );
});
this.addEventListener('fetch', event => {
    // request.mode = navigate isn't supported in all browsers
    // so include a check for Accept: text/html header.
    if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
        event.respondWith(
            fetch(event.request.url).catch(error => {
                // Return the offline page
                return caches.match(offlineUrl);
            })
        );
    }
    else{
        // Respond with everything else if we can
        event.respondWith(caches.match(event.request)
            .then(function (response) {
                return response || fetch(event.request);
            })
        );
   }
});

调试代码看起来一切正常,(执行的最后一行是返回caches.match(offlineurl))但是没有渲染离线页面,我得到了cachebuster错误。在cachebuster上google上并不多。任何见解都将不胜感激。

1 个答案:

答案 0 :(得分:0)

我发现当我在localhost上运行时发生此错误,当我将应用程序移植到https服务器(heroku)时,offline.html按预期运行