简体   繁体   中英

Can't cache simple html file with service-worker

I'm creating a page that shows a message when the user is offline, but when my service-worker tries to cache the page, always throws on Chrome console:

service-worker.js?v=1:1 Uncaught (in promise) DOMException: Quota exceeded. Promise rejected (async) addEventListener.event @ service-worker.js?v=1:10

service-worker registration:

if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./assets/app/js/service-worker.js?v=1').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);
});}

service-worker:

 'use strict';

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

this.addEventListener('install', event => {
    event.waitUntil(
        caches.open(currentCache.offline).then(function (cache) {
            return cache.addAll([
                offlineUrl
            ]);
        })
    );
});


this.addEventListener('fetch', event => {

    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 caches.match(offlineUrl);
            })
        );
    }
    else {
        event.respondWith(caches.match(event.request)
            .then(function (response) {
                return response || fetch(event.request);
            })
        );
    }
});

offline.html:

<div> offline test </div>

I already deleted all caches and it says "Quota exceeded", any idea?

Thanks.

If you want to use service workers in production I recommended using sw-precache plugin (for gulp or web pack) or workbox . After that you can set cache file URLs in bundler. Example with webpack and sw-precache from the real project:

    new SWPrecacheWebpackPlugin(
        {
            cacheId: "static-cache",
            filepath:  __dirname + "/app/public/sw.js",
            stripPrefix: __dirname + "/app/public/",
            replacePrefix: "/",
            staticFileGlobs: [
                __dirname + "/app/public/dist/**/*.{js,html,css,eot,ttf,woff,woff2}",
                __dirname + "/app/public/img/**/*.{png,jpg,gif,svg}",
                __dirname + '/app/public/offline.html' /* here you can set offline urls*/
            ],
            navigateFallback: __dirname + "/app/public/index.html"
        }
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM