首次加载后,Service Worker缓存会中断PDF

时间:2019-01-04 19:09:38

标签: javascript google-chrome caching service-worker

我正在使用sw-toolbox在我的一个客户网站上启用缓存。它通常运行良好,但出于某些原因,它会在首次加载后破坏PDF。我怀疑当它将PDF保存到缓存时,它们会以某种方式被破坏,但是我仍然可以从损坏的页面在本地保存PDF,它会很好地打开。

这是我的服务人员:

((global) => {
    // disable the service worker for post previews
    global.addEventListener("fetch", (event) => {
        if (event.request.url.match(/preview=true/)) {
            return;
        }
    });

    // ensure the service worker takes over as soon as possible
    global.addEventListener("install", event => event.waitUntil(global.skipWaiting()));
    global.addEventListener("activate", event => event.waitUntil(global.clients.claim()));

    // set up the cache
    global.toolbox.precache(["/", "/offline/"]);

    global.toolbox.router.get("/wp-content/uploads/(.*)", toolbox.cacheFirst);
    global.toolbox.router.get("/(.*)", toolbox.networkFirst, { NetworkTimeoutSeconds: 5 });

    // redirect offline queries to offline page
    self.toolbox.router.get("/(.*)", function (req, vals, opts) {
        return toolbox.networkFirst(req, vals, opts).catch((error) => {
            if (req.method === "GET" && req.headers.get("accept").includes("text/html")) {
                return toolbox.cacheOnly(new Request("/offline/"), vals, opts);
            }

            throw error;
        });
    });
})(self);

我尝试过的一些事情:

  • 添加一条附加路线global.toolbox.router.get("/wp-content/uploads/(.*).pdf", toolbox.networkOnly);
  • 更改/wp-content/uploads/(.*)路由以重定向到带有标头“ no-cache”的PDF URL

    global.toolbox.router.get("/wp-content/uploads/(.*)", function (req, vals, opts) {
        if (req.url.match(/\.pdf$/)) {
            const pdf_headers = new Headers();
    
            pdf_headers.append("Content-Type", "application/pdf");
    
            return toolbox.networkOnly(new Request(req.url, {
                method:  "GET",
                headers: pdf_headers,
                mode:    "same-origin",
                cache:   "no-cache",
            }), vals, opts);
        } else {
            return toolbox.cacheFirst;
        }
    });
    
  • 排除PDF的方式与排除preview=true的方式相同:

    global.addEventListener("fetch", (event) => {
        if (event.request.url.match(/preview=true/) || event.request.url.match(/\.pdf$/)) {
            return;
        }
    });
    

我没有主意,不胜感激。测试页面位于此处:https://www.westmontparks.org/about-us/board-minutesbid-docs/

1 个答案:

答案 0 :(得分:2)

这可能与影响Chrome 71版的this chrome bug有关。