Cache in service worker is undefined

I've having problems registering my service worker. When I try to register it, the browser complains that "Uncaught (in promise) TypeError: Cannot read property 'addAll' of undefined" It's breaking on line 6, where I try to addAll to the cache. I thought the open method creates the cache object so why is it undefined?

"use strict";
self.addEventListener('install', event => { event.waitUntil( caches.open('test').then(function(cache) { return cache.addAll([ '/index.html', '/' ]); })
);
});
self.addEventListener('activate', event => {
event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', event => {
event.respondWith( caches.match(event.request).then(response => { return response || fetch(event.request); })
);
});
3

4 Answers

It seems the Cache API is not working in the browser you are using to view your site.

I had this error come up when starting my web app in debug mode through visual studio which launches it's own instance of Chrome. For some reason the Cache API did not work there.

I used the address seen there in a regular instance of Chrome and everything worked correctly.

2

I'm not sure what your set up is regarding where your site and code are hosted, but I think I've figured out the issue here.

I've done little experimentation (Version 73.0.3683.103 (Official Build) (64-bit)), and it appears that chrome won't give you access or otherwise construct the caches object on insecure origins.

It does appear to be lenient for localhost though.

Edit: After some further digging for information/documentation, I stumbled upon , which also confirms is treated as secure.

Just ran in to this earlier today and we ended up filing this bug on Chromium:

The root cause here (or at least one root cause) is pretty strange. If, when launching Chrome, you or your IDE set the --user-data-dir switch to a path that is longer than 133 characters, the service-worker cache API blows up, and will always return undefined. Ultimately, this is because the cache storage path inside the user-data-dir is already pretty long, and it ends up hitting the 260 char file path limit on Windows.

If you can set the --user-data-dir to something shorter than this, it should work fine. Another option would be to enable NTFS "long file paths" on Windows via group policy.

1

caches are part of the property of window but in the new version of javascript you may directly access on it through;

const { caches } = self;

UPDATE:

web worker does not have access directly on the global-state or in DOM instead, you must used self to access it, click here for more info about

Welcome :)

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like