在Service Worker中引发错误“未捕获(承诺)DOMException”

时间:2019-04-17 18:13:27

标签: javascript css html5 service-worker

我正在用HTML5运行一个页面,并且我已经使用bitsofcode的教程(https://bitsofco.de/setting-up-a-basic-service-worker/)来实现我的第一个服务工作者。

页面在one.com上设置并通过cloudflare运行。

我添加了一些缓存文件,但其他文件从源头上是完整的。

Chrome控制台给我这个错误:

  

未捕获(承诺)的DOMException service-worker.js:1

我知道它会启动,因为在出​​现错误之前,我得到了

  

[ServiceWorker]已安装   [ServiceWorker]缓存cacheFiles

查看日志,我看到以下消息:

Console: {
  "lineNumber":24,
  "message":"[ServiceWorker] Installed",
  "message_level":1,
  "sourceIdentifier":3,
  "sourceURL":"https://WWW.MYURL.COM/service-worker.js"
}

Console: {
  "lineNumber":33,
  "message":"[ServiceWorker] Caching cacheFiles",
  "message_level":1,
  "sourceIdentifier":3,
  "sourceURL":"https://WWW.MYURL.COM/service-worker.js"
}

Error: {
  "columnNumber":-1,
  "lineNumber":-1,
  "message":"ServiceWorker failed to install: ServiceWorker failed to handle event (event.waitUntil Promise rejected)",
  "sourceURL":""
}

Console: {
  "lineNumber":0,
  "message":"Uncaught (in promise) InvalidStateError: Cache.addAll(): duplicate requests (https://WWW.MYURL.COM/favicon-32x32.png)",
  "message_level":3,
  "sourceIdentifier":1,
  "sourceURL":"https://WWW.MYURL.COM/service-worker.js"
}

Service-worker.js

var cacheName = 'v7'; 

// Default files to always cache
var cacheFiles = [
    './',
    './index.html',
    './favicon-96x96.png',
    './favicon-196x196.png',
    './favicon-128.png',
    './favicon-16x16.png',
    './favicon-32x32.png',
    './favicon-32x32.png',
    './manifest.json',
    './assets/css/images/bg2.jpg',
    './assets/css/images/bg2.webp',
    './assets/css/font-awesome.min.css',
    './assets/fonts/fontawesome-webfont.woff2?v=4.7.0',
    './assets/css/main.css',
    'https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,900'
]


self.addEventListener('install', function(e) {
    console.log('[ServiceWorker] Installed');

    // e.waitUntil Delays the event until the Promise is resolved
    e.waitUntil(

        // Open the cache
        caches.open(cacheName).then(function(cache) {

            // Add all the default files to the cache
            console.log('[ServiceWorker] Caching cacheFiles');
            return cache.addAll(cacheFiles);
        })
    ); // end e.waitUntil
});


self.addEventListener('activate', function(e) {
    console.log('[ServiceWorker] Activated');

    e.waitUntil(

        // Get all the cache keys (cacheName)
        caches.keys().then(function(cacheNames) {
            return Promise.all(cacheNames.map(function(thisCacheName) {

                // If a cached item is saved under a previous cacheName
                if (thisCacheName !== cacheName) {

                    // Delete that cached file
                    console.log('[ServiceWorker] Removing Cached Files from Cache - ', thisCacheName);
                    return caches.delete(thisCacheName);
                }
            }));
        })
    ); // end e.waitUntil

});


self.addEventListener('fetch', function(e) {
    console.log('[ServiceWorker] Fetch', e.request.url);

    // e.respondWidth Responds to the fetch event
    e.respondWith(

        // Check in cache for the request being made
        caches.match(e.request)


            .then(function(response) {

                // If the request is in the cache
                if ( response ) {
                    console.log("[ServiceWorker] Found in Cache", e.request.url, response);
                    // Return the cached version
                    return response;
                }

                // If the request is NOT in the cache, fetch and cache

                var requestClone = e.request.clone();
                fetch(requestClone)
                    .then(function(response) {

                        if ( !response ) {
                            console.log("[ServiceWorker] No response from fetch ")
                            return response;
                        }

                        var responseClone = response.clone();

                        //  Open the cache
                        caches.open(cacheName).then(function(cache) {

                            // Put the fetched response in the cache
                            cache.put(e.request, responseClone);
                            console.log('[ServiceWorker] New Data Cached', e.request.url);

                            // Return the response
                            return response;

                        }); // end caches.open

                    })
                    .catch(function(err) {
                        console.log('[ServiceWorker] Error Fetching & Caching New Data', err);
                    });


            }) // end caches.match(e.request)
    ); // end e.respondWith
});

SW的注册(最后输入我的html正文中)

<script type="text/javascript">
        if ('serviceWorker' in navigator) {
          navigator.serviceWorker.register('service-worker.js');
        };      
</script>

1 个答案:

答案 0 :(得分:0)

您不能多次将相同的资源提供给Cache.addAll。

您有两次favicon-32x32.png。您也可以从最后一个控制台消息中看到它:)