javascript 渐进式 Web 应用程序“无法脱机工作”错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46541071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:45:18  来源:igfitidea点击:

Progressive Web App "does not work offline" error

javascriptandroidgoogle-chromeprogressive-web-appslighthouse

提问by StampyCode

I have written a progressive web app, following all available guides and examples, but for some reason when I click the Add to homescreenbutton, I keep getting this mysterious error:

我已经按照所有可用的指南和示例编写了一个渐进式 Web 应用程序,但是由于某种原因,当我单击Add to homescreen按钮时,我不断收到这个神秘的错误:

Site cannot be installed: does not work offline

The major difference between my PWA and the examples, is that mine is running purely in a non-root path of the domain, so I have had to add extra paths to the configs in various places so the app is restricted to the non-root folder.

我的 PWA 和示例之间的主要区别在于,我的 PWA 纯粹是在域的非根路径中运行,所以我不得不在不同位置为配置添加额外的路径,因此应用程序仅限于非根文件夹。

The Google Lighthousesite doesn't help much either, giving a very similar message.

谷歌灯塔网站没有太大的帮助或者,给人一种非常类似的消息。

Can anyone suggest what this error might be caused by?

谁能建议这个错误可能是由什么引起的?

回答by StampyCode

So it took me a couple of hours, but I eventually figured out that there is a required scopeparameter that you need to specify in the client JavaScript when connecting to the serviceworker, if it's not running on the root (/) path.

所以我花了几个小时,但我最终发现scope在连接到 serviceworker 时,您需要在客户端 JavaScript 中指定一个必需参数,如果它不在根 ( /) 路径上运行。

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('sw.js?v2', {
        scope: '.' // <--- THIS BIT IS REQUIRED
    }).then(function(registration) {
        // Registration was successful
        console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }, function(err) {
        // registration failed :(
        console.log('ServiceWorker registration failed: ', err);
    });
}

You can see the working product here:

您可以在此处查看工作产品:

I hope my pain can save someone else some time.

我希望我的痛苦可以拯救别人一些时间。

回答by mixel

Also you need to define fetchlistener in a service worker file:

您还需要fetch在服务工作者文件中定义侦听器:

this.addEventListener('fetch', function (event) {
    // it can be empty if you just want to get rid of that error
});