service-worker - 将 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
我确定我在这里遗漏了一些东西,但我不知道它是什么。
解决方案
我找到了一种解决方法,但仍然不确定为什么 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]) {...})
推荐阅读
- python - Python - 在json文件中转换列表
- python - 为了修复 +: int 和 tuple 的操作数类型错误,我与 jj 有什么关系?
- gensim - 为什么 Gensim Doc2vec 对象返回空文档标签?
- php - WordPress:过滤链接中某些字符串的内容并将元素更改为跨度
- flutter - 如何在颤振图表中添加标签?
- html - 使用 Twitter 引导程序将列居中不工作
- power-automate - 对图形的 Http 调用和异步模式似乎不起作用
- javascript - 如何从具有动态值的字符串中提取数组?
- r - geom_col 分配了错误的自变量
- linux - Tcp连接泄漏问题