William Walseth
William Walseth

Reputation: 2923

Service Worker Fails on caches.open()

I'm trying to get a basic service worker up and running.

The problem I have is that when I run "caches.open()", the browser throws a

sw.js:1 Uncaught (in promise) DOMException: Unexpected internal error

Commenting out the caches.open removes the exception.

How can I get more information from the browser to tell me what's wrong?

Here's the service worker and registration code.

var CACHE_NAME = 'pwacache-v1';

var urlsToCache = [
    '/',
    'main.css'
];


self.addEventListener('install', function (event) {
    // Perform install steps
    console.log('install');
    try {
        event.waitUntil(getFiles());
    } catch (ex) {
        console.log(ex);
    }
});

function getFiles() {
    console.log('opening: ' + CACHE_NAME );
    /*
        triggers Uncaught (in promise) DOMException: Unexpected internal error
    */
    caches.open(CACHE_NAME).then(function (cache) {
        return Promise.all(
            urlsToCache.map(function (url) {
                console.log(url);
                return cache.add(url).catch(function (reason) {
                    console.log([url + "failed: " + String(reason)]);
                });
            }) // end of map
        );
    });
    console.log('waiting 3...')
}

And the registration code

// https://developers.google.com/web/fundamentals/primers/service-workers/registration
if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('sw.js');
  });
}

I do see the sw.js registered in Chrome's 'Application' tab.

Upvotes: 1

Views: 3085

Answers (1)

Ben Kelly
Ben Kelly

Reputation: 1344

You need to return a promise from getFiles() in order for the event.waitUntil() to actually wait for the async work. So I recommend returning the promise returned by your promise chain started with caches.open().

Without this its possible the service worker is being terminated before the async work can complete.

Upvotes: 1

Related Questions