我正在尝试在测试页面中实现Service Worker
。我的最终目标是一个可以离线运行的应用程序。文件夹结构如下
/myApp
...
/static
/mod
/practice
service-worker.js
worker-directives.js
foopage.js
/templates
/practice
foopage.html
我正在注册一个 Service Worker,如下所示(在 service-worker.js
中):
navigator.serviceWorker.register('../static/mod/practice/service-worker.js').then(function(reg) {
console.log('Registration succeeded. Scope is ' + reg.scope);
...
}
在控制台中我看到
注册成功。范围是 https://example.com/static/mod/practice/
如果我的页面位于 https://example.com/practice/foopage
,我是否需要确保我的 service Worker
范围为 https://example.com/practice/foopage
?
如果我尝试在 register
函数调用中定义范围,例如
navigator.serviceWorker.register('../static/mod/practice/service-worker.js', { scope: '/practice/foopage/' }).then(function(reg) {
...
}
我收到错误
Registration failed with SecurityError: Failed to register a ServiceWorker: The path of the provided scope ('/practice/foopage/') is not under the max scope allowed ('/static/mod/practice/'). Adjust the scope, move the Service Worker script, or use the Service-Worker-Allowed HTTP header to allow the scope.
问题是:范围到底指的是什么?它是 service Worker
最终控制的 URL 集合吗?我需要将 service-workers.js
移到其他地方吗?如果是的话,在哪里?
最佳答案
Service Worker 基本上是 Web 应用程序和互联网之间的代理,因此如果需要,它可以拦截对网络的调用。
此实例中的范围是指服务工作线程能够拦截网络调用的路径。可以使用 scope
属性显式定义它将覆盖的范围。但是:
服务工作线程只能拦截源自服务工作线程脚本所在的当前目录及其子目录范围内的请求。 Or as MDN states :
The service worker will only catch requests from clients under the service worker's scope.
The max scope for a service worker is the location of the worker.
由于您的 Service Worker 位于 /static/mod/practice/
中,因此不允许将其范围设置为 /practice/foopage/
。向其他主机发出请求,例如https://stackoverflow.com/foo
,任何情况下都可以拦截。
确保 Service Worker 能够拦截所需的所有调用的最简单方法是将其放置在 Web 应用程序的根目录中 (/
)。您还可以使用 http header 覆盖默认限制并手动设置范围(请参阅 Ashraf Sabry 的回答)。
关于javascript - 了解 Service Worker 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35780397/