PWA-子目录中的服务工作者JS

时间:2019-10-01 13:10:04

标签: service-worker progressive-web-apps

我尝试将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');
}

1 个答案:

答案 0 :(得分:2)

如果我做同样的事情,会出现以下错误

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/' }