首页 > 解决方案 > 将 sw 放在子文件夹中时,navigator.serviceWorker.ready 不会触发

问题描述

我们的应用程序由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>

要注册 serviceworker,我需要添加子文件夹,如下所示

// 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.

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

// Inside of file.js
navigator.serviceWorker.ready.then(...) // Will not fire

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

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

{ scope: '/' } // Will fail with outside root error
{ scope: '/MyApp' } // Works, but still no ready event

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

标签: service-worker

解决方案


我找到了一种解决方法,但仍然不确定为什么 ready 没有触发。

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]) {...})

推荐阅读