当 sw 放置在子文件夹中时 navigator.serviceWorker.ready 不会触发

Lar*_*rsi 5 service-worker

我们的应用程序由https://myserver.com/myapp提供服务(由虚拟应用程序中的 IIS 提供)

从https://myserver.com/myapp返回的 HTML为:

<html>
  <!-- This file is served as a virtual application from https://myserver.com/myapp-->
  <head>
    <script src="/myapp/file.js"></script>
  </head>
<body>
</body>
Run Code Online (Sandbox Code Playgroud)

要注册服务人员,我需要添加子文件夹,如下所示

// This does not work since the app is served from /myapp
navigator.serviceWorker.register("/sw.js")  // Fail, will try loading https://myServer.com/sw.js

// This works (registration successful)
navigator.serviceWorker.register("/myapp/sw.js")  // This will register the sw.
Run Code Online (Sandbox Code Playgroud)

当我尝试使用正在等待就绪事件的服务工作者时,出现问题:

// Inside of file.js
navigator.serviceWorker.ready.then(...) // Will not fire
Run Code Online (Sandbox Code Playgroud)

我猜发生的情况是,ready 事件没有触发,因为 serviceworker“认为”它是从名为“MyApp”的子文件夹安装的,但是当 file.js 运行并尝试使用 serviceworker 时,它看起来像文件.js 从 root 提供服务,因此超出了 serviceworker 的范围。

关于如何处理这个问题有什么想法吗?我尝试使用范围参数,但我认为这仅用于限制范围,而不是扩展范围。

{ scope: '/' } // Will fail with outside root error
{ scope: '/MyApp' } // Works, but still no ready event
Run Code Online (Sandbox Code Playgroud)

我确信我在这里遗漏了一些东西,但我不知道它是什么。

Lar*_*rsi 3

我找到了解决方法,但仍然不确定为什么准备就绪没有触发。

navigator.serviceWorker.ready.then(function(reg){...}) // Will not fire

// Instead, assume registred and active, then this is a workaround
navigator.serviceWorker.getRegistrations().then(function ([reg]) {...})
Run Code Online (Sandbox Code Playgroud)