我试图将我的 sw.js 文件放在子目录而不是根目录中。但随后我收到一条错误消息,指出无法安装服务人员。
是否真的有必要将该文件放在根目录中,还是我只是遗漏了什么?
JS 代码:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/js/pwa/sw.js', { scope: '/js/pwa' }).then(function(reg) {
console.log('Successfully registered. Scope is ' + reg.scope);
}).catch(function(error) {
console.log('Registering failed ' + error);
});
} else {
console.log('Service worker can not be registered on this device');
}
最佳答案
如果我做同样的事情,我会得到以下错误
Registering failed SecurityError: Failed to register a ServiceWorker: The path of the provided scope ('/js/pwa') is not under the max scope allowed ('/js/pwa/'). Adjust the scope, move the Service Worker script, or use the Service-Worker-Allowed HTTP header to allow the scope.
下面的部分看起来很奇怪
{ scope: '/js/pwa' }
请按如下操作
{ scope: '/js/pwa/' }
关于service-worker - PWA - 子目录中的 service-worker JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58185483/