navigator.serviceWorker is never ready

后端 未结 5 1915
既然无缘
既然无缘 2020-12-13 23:29

I registered a service worker successfully, but then the code

navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
    // Do we already h         


        
5条回答
  •  失恋的感觉
    2020-12-13 23:52

    Like said in the accepted answer, the problem is, indeed, probably because your service worker JS file is in a different path than your current page.

    By default, the scope of the service worker is the path to its JS file. If your JS file is reachable at http://www.example.com/assets/js/service-worker.js, your service worker will only work/"be ready" for URL starting with /assets/js/.

    But, you can change the scope of the service worker. First, you need to register if using the scope option:

    navigator.serviceWorker.register('http://www.example.com/assets/js/service-worker.js', {
        scope: '/',
    });
    

    If you do, just this, you will get errors in the Chrome console:

    The path of the provided scope ('/') is not under the max scope allowed ('/assets/js/'). Adjust the scope, move the Service Worker script, or use the Service-Worker-Allowed HTTP header to allow the scope.

    /admin/#/builder:1 Uncaught (in promise) DOMException: Failed to register a ServiceWorker for scope ('http://www.example.com/') with script

    ('http://www.example.com/assets/js/service-worker.js'): The path of the provided scope ('/') is not under the max scope allowed ('/assets/js/'). Adjust the scope, move the Service Worker script, or use the Service-Worker-Allowed HTTP header to allow the scope.

    You then need to create an .htacess file at the root of your website with the following content:

    
        
            Header set Service-Worker-Allowed: /
        
    
    

提交回复
热议问题