navigator.serviceWorker is never ready

2019-02-05 13:16发布

问题:

I registered a service worker successfully, but then the code

navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
    // Do we already have a push message subscription?
    ....

hangs -- the function is never called. Why?

回答1:

The problem was that the service-worker.js file was stored in an assets sub-directory.

Don't do that: store the service-worker.js in the root of your app (or higher). That way your app can access the service-worker.

See HTML5Rocks article --

One subtlety with the register method is the location of the service worker file. You'll notice in this case that the service worker file is at the root of the domain. This means that the service worker's scope will be the entire origin. In other words, this service worker will receive fetch events for everything on this domain. If we register the service worker file at /example/sw.js, then the service worker would only see fetch events for pages whose URL starts with /example/ (i.e. /example/page1/, /example/page2/).

Added

A new problem is that the serviceworker is never ready if the page is hard-reloaded. Subsequent soft page reloads work fine. Google's own sample code fails. See the Chrome bug report.

The bug fix was included with Chrome 44.