Progressive Web App “does not work offline” error

走远了吗. 提交于 2019-12-09 06:54:15

问题


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

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.

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

Can anyone suggest what this error might be caused by?


回答1:


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

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:

  • App: https://stampy.me/pwgen/
  • Manifest file: https://stampy.me/pwgen/manifest.json
  • ServiceWorker file: https://stampy.me/pwgen/sw.js
  • App script: https://stampy.me/pwgen/script.js (scroll to bottom for PWA code)

I hope my pain can save someone else some time.




回答2:


Also you need to define fetch listener in a service worker file:

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


来源:https://stackoverflow.com/questions/46541071/progressive-web-app-does-not-work-offline-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!