【问题标题】:Service worker not returning a cached response, unless url contains a slash at the endService Worker 不返回缓存的响应,除非 url 末尾包含斜杠
【发布时间】:2020-01-28 18:47:19
【问题描述】:

我在https://example.com/customer/app 有一个 SPA。

当您访问该页面时,如果您没有登录,SPA 会将 #/login 附加到 url,所以现在它显示为 https://example.com/customer/app#/login

有一个 Service Worker 正在运行,安装范围为 /customer/app

当应用离线时,我试图从我的服务人员返回 200 响应。为简单起见,我目前对我的应用程序中的所有内容都使用了一个虚拟响应:

customer-sw.js 读取:

self.addEventListener('install', function(e) {
    // Do nothing for now.
});

self.addEventListener('fetch', function(event) {
    event.respondWith( new Response('Hello world') );
});

这意味着如果服务工作者安装正确,每个请求都应该产生一个简单的Hello world(就好像它是一个以这种方式缓存的页面)。唯一的问题是,除非网址末尾有斜杠,即/customer/app/ 而不是/customer/app,否则我无法让它工作。对/customer/app 的请求会导致检索实际页面,而对/customer/app/ 的请求(或任何其他低于此的请求)会导致Hello world

我想我会发布这个问题,以防其他人对为什么他们不能让他们的服务人员用缓存页面做出响应感到困惑。似乎秘诀是确保您在网址末尾使用斜杠。我希望Google's documentation 能指出这个小细节。

不过,出于好奇,有没有办法让它与/customer/app 一起工作?现在看起来我需要将/customer/app 重定向到/customer/app/ 并进行测试以确保没有任何损坏。

【问题讨论】:

    标签: caching service-worker progressive-web-apps service-worker-events


    【解决方案1】:

    service worker 的默认作用域是脚本所在的路径。 /customer/app 被视为高于 /customer/app/

    您可以使用Service-Worker-Allowed 响应标头更改此行为并允许更大的范围:

    https://developers.google.com/web/ilt/pwa/introduction-to-service-worker#registration_and_scope

    https://w3c.github.io/ServiceWorker/#service-worker-script-response

    // Default scope:
    // Maximum allowed scope defaults to the path the script sits in
    // "/js/" in this example
    navigator.serviceWorker.register("/js/sw.js").then(() => {
      console.log("Install succeeded with the default scope '/js/'.");
    });
    
    
    // Set the scope to an upper path of the script location
    // Response included "Service-Worker-Allowed : /"
    navigator.serviceWorker.register("/js/sw.js", { scope: "/" }).then(() => {
      console.log("Install succeeded as the max allowed scope was overriden to '/'.");
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-27
      • 2016-12-22
      • 2012-10-27
      • 1970-01-01
      • 2018-02-18
      • 2021-09-07
      相关资源
      最近更新 更多