更改预缓存URL的/ Service Worker范围

时间:2019-11-25 14:32:18

标签: service-worker progressive-web-apps workbox

我正在尝试使用Workbox&Gulp构建可预缓存特定资产的服务工作程序,但是,我遇到了一个问题,其中URL注入到预缓存清单中是无效的。

我认为这是由于服务工作者的范围所致,因为它位于根目录中,并且我希望它将所有内容都缓存在“公共”目录中。我希望我的URL是public/assets/image_1.png,但是它们将以assets/image_1.png的形式添加到预缓存清单中,并且assets文件夹之外的任何内容都将被忽略。

我可以通过将service-worker.js添加到公共目录中来更正URL,但是服务工作者无法在浏览器中服务。我曾尝试在Gulp中操纵globPatterns,但这会引发语法错误。

以前有人遇到过这个问题吗?我是服务人员的新手,还没有找到任何文章/ GitHub页面/ SO帖子可以帮助我解决问题,因此我们非常感谢您的帮助。希望这对某人来说是有意义的。

目录:

.
+-- gulpfile.js
+-- package.json
+-- service-worker.js
+-- index.php
+-- public
|   +-- style.css
|   +-- script.js
|   +-- assets
|       +-- image_1.png
|       +-- image_2.png
+-- pwa
|   +-- dev-service-worker.js

gulpfile.js

gulp.task('service-worker', () => {
    return workboxBuild.injectManifest({
        swSrc: 'pwa/dev-service-worker.js',
        swDest: 'service-worker.js',
        globDirectory: 'public',
        globPatterns: [
            '**\/*.{js,css,html,png,jpg,jpeg,woff2,ttf,eot,svg}',
        ]
    }).then(({count, size, warnings}) => {
        // Optionally, log any warnings and details.
        warnings.forEach(console.warn);
        console.log(`${count} files will be precached, totaling ${size} bytes.`);
    });
});

service-worker.js

try {

    importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.2.0/workbox-sw.js');

    const LOCATION_ORIGIN = self.location.origin;
    const PRECACHE_PREFIX = "test";
    const PRECACHE_NAME = "precache";
    const PRECACHE_SUFFIX = "v2";
    const WORKBOX_PRECACHE = `${PRECACHE_PREFIX}-${PRECACHE_NAME}-${PRECACHE_SUFFIX}`;

    const URL_RULES = {
        "page-required": [
            'public/'
        ],
        "page-denied": [
            "\/some", "\/denied", "/^\/urls/"
        ],
        "static-required": [
            /\.(?:js,css,html,png,jpg,jpeg,woff2,ttf,eot,svg)$/
        ],
        "static-denied": [
            "\/some", "\/denied", "/^\/urls/"
        ]
    };

    if(workbox) {
        workbox.setConfig({ debug: true });

        workbox.clientsClaim();
        workbox.skipWaiting();

        workbox.core.setCacheNameDetails({
            prefix: PRECACHE_PREFIX,
            suffix: PRECACHE_SUFFIX,
            precache: PRECACHE_NAME
        });

        workbox.precaching.precacheAndRoute([]);

        workbox.routing.registerRoute(matchPage, serveOfflinePage);

        workbox.routing.registerRoute(
            matchStaticResource,
            workbox.strategies.cacheFirst({
                cacheName: 'test-runtime-cache',
                plugins: [
                    new workbox.expiration.Plugin({
                        maxAgeSeconds: 1 * 24 * 60 * 60 // 1 day
                    })
                ]
            })
        );

        function matchPage({ url }) {
            return URL_RULES["page-required"].every(pattern => matchPattern(url.pathname, pattern))
            && !URL_RULES["page-denied"].some(pattern => matchPattern(url.pathname, pattern));
        }

        function serveOfflinePage({ url, event }) {
            return fetch(event.request)
            .then(response => {
                if (response.status === 401) {
                    self.registration.unregister()
                    .then(() => self.clients.matchAll())
                    .then(clients => {
                        clients.forEach(client => client.navigate(client.url))
                    })
                    .catch(error => console.log(`Unable to authenticate and/or reload: ${error}`))
                }
                return response;
            })
            .catch(error => {
                return caches.open(WORKBOX_PRECACHE)
                .then(cache => {
                    return cache.match('/offline.html')
                    .then(response => response)
                })
            });
        }

        function matchStaticResource({ url }) {
            return url.href.indexOf(LOCATION_ORIGIN) !== -1 &&
            URL_RULES["static-required"].every(pattern => matchPattern(url.pathname, pattern)) &&
            !URL_RULES["static-denied"].some(pattern => matchPattern(url.pathname, pattern));
        }

        function matchPattern(urlPath, pattern) {
            if (typeof pattern === "string") {
                return urlPath.indexOf(pattern) !== -1;
            } else if (pattern instanceof RegExp) {
                return pattern.test(urlPath);
            }
        }
    }

} catch(e) {
    // Prevent caching logic on fail (mainly protecting against importScripts() failure)
}

1 个答案:

答案 0 :(得分:0)

对我来说,答案是在Gulpfile中设置更多绝对路径。 我为根添加了Action,然后给了./一条不同的路径。

这最终是一个简单的修复程序,因此如果有人遇到类似问题,我将在这里保留。

globPatterns